我有以下查询:
set @DataEnd = '
select top 1 datetime
from IntradayHistory.dbo.IntradayDataHistory' + @product + '
where TickerID = ' + cast(@ticker as nvarchar(24)) + '
order by datetime desc
'
exec(@DateEnd)
这应该只返回1个值,它确实:
但是,由于我需要将该值作为动态查询的DateTime,我应该怎么做?
答案 0 :(得分:2)
使用sp_executesql,您可以将输出参数发送到动态查询。
DECLARE @sqlCommand NVARCHAR(MAX);
DECLARE @dateEnd DATETIME;
SET @sqlCommand = '
select top 1 @retVal = datetime
from IntradayHistory.dbo.IntradayDataHistory' + @product + '
where TickerID = ' + cast(@ticker as nvarchar(24)) + '
order by datetime desc
';
EXECUTE sp_executesql @sqlCommand, N'@retVal DATETIME OUTPUT', @retVal=@dateEnd OUTPUT;
SELECT @dateEnd;
选项B:
您可以使用临时表来存储动态查询的结果。
DECLARE @sqlCommand NVARCHAR(MAX);
SET @sqlCommand = '
select top 1 datetime
from IntradayHistory.dbo.IntradayDataHistory' + @product + '
where TickerID = ' + cast(@ticker as nvarchar(24)) + '
order by datetime desc
';
CREATE TABLE #temp1 (Result DATETIME);
INSERT INTO #temp1 EXEC (@sqlCommand);
SELECT * FROM #temp1;