从动态SQL SELECT中获取单个值

时间:2013-10-01 09:24:45

标签: sql-server

如何从以下动态SQL中检索值并将其分配给变量?

SET @SQLString = N'SELECT TOP 1 D'+CAST(DAY(@dateTime)AS varchar(MAX)) 
               + ' FROM TabelForMonthCurrent'
               + ' WHERE empContractID=' + CAST(@pEmpContractID AS nvarchar(MAX))
               + ' AND Year=' + CAST(YEAR(@dateTime) AS nvarchar(MAX)) 
               + ' AND Month=' + CAST(MONTH(@dateTime) AS nvarchar(MAX))

1 个答案:

答案 0 :(得分:1)

将动态SQL更改为SET @SQLString = N'SELECT @result = ...

然后使用sp_executesql

DECLARE @result NVARCHAR(MAX)
EXEC sp_executesql
    @query = @SQLString, 
    @params = N'@result NVARCHAR(MAX) OUTPUT', 
    @result = @result OUTPUT