本文介紹了SQL Server Dynamic SQL-從表列表中獲取輸出的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我正試圖遍歷一個(gè)包含表名列表的TEMP表變量。我想簡(jiǎn)單地計(jì)算每個(gè)表中DateTracked列大于30天的行數(shù)。我在動(dòng)態(tài)更改from@tblName變量以存儲(chǔ)記錄計(jì)數(shù),然后將其插入到我的跟蹤表中時(shí)遇到了問(wèn)題。最后,我將使用游標(biāo)遍歷每個(gè)表,但我只想首先為單個(gè)表記錄這一邏輯。以下是我的測(cè)試代碼:
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對(duì)問(wèn)題提供答案。
這篇關(guān)于SQL Server Dynamic SQL-從表列表中獲取輸出的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,