T-SQL选择语句作为变量,并将结果放到另一个变量中

时间:2021-01-09 09:11:17

This is the last part of my function:

这是我的最后一部分职能:

 SET @query = (N'SELECT [' +@outColumn+'] FROM [Production].[dbo].[v_time] WHERE textile LIKE '''+@outTextile+'''')

I tried like this: (also I tried with 'exec sp_executesql(@query)' and it doesn't work)

我这样尝试:(我还尝试了'exec sp_executesql(@query)',但它不起作用)

 SET @output = (@query)
 RETURN @output

And as result I get is the exact SQL query I wanted. But, how to RUN (execute) @query and its result (in this case it is a decimal number) put in variable @output and return??

结果我得到了我想要的SQL查询。但是,如何运行(执行)@query及其结果(在本例中是十进制数)并放入变量@output和return?

1 个解决方案

#1


3  

Try something like.....

尝试像.....

Declare @query     NVarchar(MAX)
      , @outColumn SYSNAME
      , @Out       DECIMAL(10,2)

SET @query =  N' SELECT TOP 1 @Out = ' +QUOTENAME(@outColumn) 
           +  N' FROM [Production].[dbo].[v_time] '
           +  N' WHERE textile LIKE ''%'' + @outTextile + ''%'''

 Exec sp_executesql @query
                   ,N'@outTextile VARCHAR(50) , @Out DECIMAL(10,2) OUTPUT'
                   ,@outTextile
                   ,@Out OUTPUT 

#1


3  

Try something like.....

尝试像.....

Declare @query     NVarchar(MAX)
      , @outColumn SYSNAME
      , @Out       DECIMAL(10,2)

SET @query =  N' SELECT TOP 1 @Out = ' +QUOTENAME(@outColumn) 
           +  N' FROM [Production].[dbo].[v_time] '
           +  N' WHERE textile LIKE ''%'' + @outTextile + ''%'''

 Exec sp_executesql @query
                   ,N'@outTextile VARCHAR(50) , @Out DECIMAL(10,2) OUTPUT'
                   ,@outTextile
                   ,@Out OUTPUT