Is there a way to call a function by referring to a database field? Example:There are 2 ProductIDs. Each ProductId has been assigned a different function. In my code, I have a ProductId and I have to look up and call the function that is assigned to that ProductId. ProductId FunctionName 1 dbo.SampleFunction1 2 dbo.SampleFunction2
I know that it's possible to do this with stored procedures, but I'd like to know if it can be done with functions.Here is some sample code to show what I am trying to accomplish. Please note that the sample function code is just a quick mockup and doesn't really make sense :). --- Set up the sample functionsCREATE FUNCTION SampleFunction1 (@ProductId INT) returns @Info TABLE (ProductId INT, TestColumn VARCHAR (30)) AS BEGIN INSERT INTO @Info SELECT 1, '1 - It works!' RETURN ENDCREATE FUNCTION SampleFunction2 (@ProductId INT) returns @Info TABLE (ProductId INT, TestColumn VARCHAR (30)) AS BEGIN INSERT INTO @Info SELECT 2, '2 - It works!' RETURN END--- Set up the Lookup table DECLARE @Lookup TABLE (ProductId INT, FunctionName VARCHAR(30)) INSERT INTO @Lookup SELECT 1, 'dbo.SampleFunction1' UNION ALL SELECT 2, 'dbo.SampleFunction2' --- Find the function that goes with the given ProductId (ProdId)DECLARE @ProdId INTSET @ProdId = 1DECLARE @FunctionName VARCHAR(30)SET @FunctionName = (SELECT lkp.FunctionName FROM @lookup lkp WHERE lkp.ProductId = @ProdId)-- Here, I would like to call the function using @FunctionName, but can't figure out if it's even possible to do that.-- If this were a stored procedure, I could just use EXEC @ProcedureName. -----This is the sort of thing I'm looking for, where this type of code would call the function:-----SELECT *-----FROM (@FunctionName) -- Drop the sample functionsDROP FUNCTION SampleFunction1DROP FUNCTION SampleFunction2
Thank you for your help.