Search code examples
sqlfunctiont-sqldynamic-sql

T-sql, Running the function whose name is stored in a string variable...with something like exec...and capturing the return value


The following code works fine (Echo is a user defined function that takes a string and returns a string):

Declare @ttt varchar(max) = ''
set @ttt = dbo.Echo('sdf')
print @ttt

But the problem is that I have a configuration setting that stores the name of a function in the current database. The function must take a string parameter and return a string parameter. So I don't necessarily want to call dbo.Echo. But I want to call whatever is configured.

So what I am trying to do is something like this:

Declare @ttt varchar(max) = ''
Declare @sql varchar(Max)
Declare @func varchar(Max)
Declare @par varchar(max)
set @func = '[dbo].[Echo]'
set @par = 'sdf'
set @sql = 'set @ttt = ' + @func + '(' + '''' + @par + '''' + ')'
exec (@sql)
print @ttt

But it tells me that scaler @ttt is not declared!

So I tried like this...

Declare @ttt varchar(max) = ''
Declare @sql varchar(Max)
Declare @func varchar(Max)
Declare @par varchar(max)
set @func = '[dbo].[Echo]'
set @par = 'sdf'
set @sql = @func + '(' + '''' + @par + '''' + ')'
set @ttt = exec (@sql)
print @ttt

I get 'Incorrect syntax near the keyword exec'

How do I capture the return value and store it in @ttt?

Dear StackExchange: there is a bug on your website. I am not allowed to enter the following comment in response to the accepted answer.

Here is the comment with regard to the accepted answer: it works, but I have to declare @sql as: Declare @sql nvarchar(Max).


Solution

  • If I understand correctly, you want an output parameter:

    declare @tttx varchar(max);
    
    set @sql = 'set @ttt = ' + @func + '(' + '''' + @par + '''' + ')'
    exec sp_executesql @sql,
                       N'@ttt varchar(max) output',
                       @ttt=@tttx output;
    
    print @tttx;