如何从动态查询中获取变量的值

How To Get Value of Variable From Dynamic Query

DECLARE
    @id int = NULL, @district int = 12, @zone int = 48,
    @str nvarchar(max) = NULL, @sanctioned int = 0 

CREATE TABLE #runningTable
(
    postid int NULL,
    postname varchar(50) NULL,
    sanction int NULL DEFAULT 0,                           
    surplus int NULL DEFAULT 0,
    inposition int NULL DEFAULT 0,
    aar int NULL DEFAULT 0,
    vacant int NULL DEFAULT 0
)
                         
SET @str = 'select @sanctioned = (SUM('+@value+')) FROM staff_strength_details a 
                                            INNER JOIN school_master b ON b.udisecode = a.udisecode
                                            WHERE CONVERT(varchar, b.district_id) = ''' + CONVERT(varchar, @district) + ''' AND 
                                            CONVERT(varchar, b.zone_id) = '''  + CONVERT(varchar, @zone) + '''
                                                            
                                            @sanctioned int output
                                                                        '
EXEC sp_executesql @str, @sanctioned = @sanctioned OUTPUT

UPDATE #runningTable 
SET sanction = @sanctioned 
WHERE postid = @id

SELECT * FROM #runningTable

DROP TABLE #runningTable

在上面的查询中,我声明了一个@sanctioned变量,需要得到这个变量中动态列的总和。然后需要在动态 table #runningTable 中更新变量。但是在执行上面的查询时我得到一个错误

Procedure expects parameter '@params' of type 'ntext/nchar/nvarchar'

因此我已将 @str 声明为 nvarchar 但我仍然遇到相同的错误。

如何获取声明变量的值@sanctioned

这里有一个如何使用动态的小例子sql。它接受一个变量作为动态字符串的输入,并将单个值 sum(status) 输出到变量 @l_out1

您可以修改此示例以满足您的需要。在你的例子中,我发现你有一个语句 sum(@value),但是 @value 没有定义。

declare @str       nvarchar(4000)
declare @l_out1    int
declare @l_status1 int =1


set @str='select @l_out=sum(status) ' 
         + 'from master..spt_values '
         + 'where status=@l_status '

exec sp_executesql @str
                   ,N'@l_status INT,@l_out INT OUTPUT'
                   ,@l_status=@l_status1
                   ,@l_out=@l_out1 output

select @l_out1 as 'col1'

工作示例

https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=4ebab535a4970f478ce22547e5dd8150