1

我遇到了一个问题。我试图在 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      
4

1 回答 1

0

我认为您的问题是 INSERT 在 CTE 定义之前的定位。尝试移动它,如下所示:

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 - 也添加了

于 2013-10-16T13:11:36.857 回答