我遇到了一个问题。我试图通过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
答案 0 :(得分:0)
我认为你的问题是在CTE定义之前定位INSERT。尝试移动它,如:
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 +'
GO
;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 )
insert into WSA.dbo.TEST
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
编辑 - 哦,你在使用USE关键字切换数据库后需要GO - 同样添加了