SQL Server Dynamic SQL-从表列表中获取输出
我正试图遍历一个包含表名列表的TEMP表变量。我想简单地计算每个表中DateTracked列大于30天的行数。我在动态更改from@tblName变量以存储记录计数,然后将其插入到我的跟踪表中时遇到了问题。最后,我将使用游标遍历每个表,但我只想首先为单个表记录这一逻辑。以下是我的测试代码:
DECLARE @tblName as NVARCHAR(MAX)
DECLARE @q as NVARCHAR(MAX)
SET @q = 'Select Count(DateTracked) FROM Audit.' + @tblName + ' WHERE DateTracked > DATEADD(dd, -30, CAST(GETDATE() as date))'
--DECLARE @tblNameTable TABLE
--(
-- tableName NVARCHAR(MAX)
--)
--INSERT INTO @tblNameTable VALUES (N'myTestTable')
DECLARE @ExpectedRecordsToMove AS TABLE (col1 int)
INSERT INTO @ExpectedRecordsToMove EXECUTE sp_executesql @q, N'@tblName nvarchar(500)', @tblName = 'myTestTable'
SELECT * FROM @ExpectedRecordsToMove
解决方案
找到解决方案。
DECLARE @tblName as NVARCHAR(MAX) = 'tblAutoDispatch_DispatchStatus_Map_Tracking'
DECLARE @q as NVARCHAR(MAX) = 'SELECT Count(DateTracked) FROM Audit.' + @tblName + ' WHERE DateTracked > DATEADD(dd, -30, CAST(GETDATE() as date))'
DECLARE @ExpectedRecordsToMove TABLE
(
ExpectedRecordsToMove Int
)
INSERT INTO @ExpectedRecordsToMove
EXECUTE sp_executesql @q
SELECT * FROM @ExpectedRecordsToMove
注意:由OP对问题提供答案。
相关文章