我遇到了一个问题。我试图在 CTE 代码上的多个数据库中使用 while 循环。我收到以下错误消息
102, Level 15, State 1, Line 4 Incorrect syntax near ';'.
我现在用于所有查询的当前代码粘贴在下面......任何帮助都会很好地了解我如何遍历多个数据库。谢谢。
USE WSA
delete from TEST
GO
DECLARE @Database varchar(20), @i int
SELECT @i = 0
WHILE @i < 6
BEGIN
if @i = 0 SELECT @Database = 'Hs_Active'
if @i = 1 SELECT @Database = 'Ge_Active'
if @i = 2 SELECT @Database = 'At_Active'
if @i = 3 SELECT @Database = 'LW_Active'
if @i = 4 SELECT @Database = 'SE_Active'
if @i = 5 SELECT @Database = 'LL_Active'
execute(
'USE '+@Database +'
insert into WSA.dbo.TEST
;WITH
Credit AS
( SELECT PTNO,CD,AMT,DESCRIPTION,
ROW_NUMBER()OVER(PARTITION BY PTNO,CD ORDER BY BatchSeqID) AS Sort
FROM dbo.DTLPAYMENTS
WHERE AMT < 0 ),
Debit AS
( SELECT PTNO,CD,AMT,DESCRIPTION,
ROW_NUMBER()OVER(PARTITION BY PTNO,CD ORDER BY BatchSeqID) AS Sort
FROM dbo.DTLPAYMENTS
WHERE AMT > 0 )
SELECT ISNULL(c.PTNO,d.PTNO) AS PTNO,
ISNULL(c.CD,d.CD) AS CD,
--Credit data
c.AMT AS CRAMT,
c.DESCRIPTION AS CRDESCRIPTION,
--Debit data
d.AMT AS DBTAMT,
d.DESCRIPTION AS DBTDESCRIPTION
FROM Credit c
FULL JOIN Debit d
ON d.PTNO = c.PTNO
AND d.CD = c.CD
AND d.Sort= c.Sort
')
SELECT @i=@i+1
END