2016-04-13 5 views
0

SQLサーバー2008を使用しています。temp tableからdatabaseにデータを挿入したいとします。私はWhile loopを使用して、一時テーブルからデータベーステーブルにデータを挿入しています。 今、私は問題に直面しています:データベースに「PDBCompr」という名前のオブジェクトが既にあります

オブジェクトがすでにデータベースに存在しています。

declare @rev as int , 
    @sQuotationNo NVARCHAR(15),                      
    @sQRevNo int                        
    set @rev=(select top 1 QRevNo from PDBCompr Where QuotationNo='JCS_G1415_008' and QRevNo<>'3' order by QRevNo desc) 

    ;with cte as 
    ( 
    SELECT  
    ROW_NUMBER() OVER(ORDER BY QuotationNo) AS sSLNO,             
    [CompanyCode] ,  
    [ProjectCode] , 
    [PRevNo], 
    [CSlNo],  
    [ComprDescription] ,  
    [PID] ,  
    [RatingCode] ,  
    [Rating] ,  
    [StdSystems] ,  
    [BoosterSystems] ,  
    [GCUSystems] ,  
    [KOFSystems] ,  
    [HeaterSystems] ,  
    [OtherSystems] ,  
    [Comments] ,  
    [Currency1] ,  
    [UnitPrice1] ,  
    [Currency2] ,  
    [ExchRate2] ,  
    [UnitPrice2] ,  
    [Currency3],  
    [ExchRate3] ,  
    [UnitPrice3] ,  
    [CreateId] ,  
    [CreateDate] ,  
    [UpdateId] ,  
    [UpdateDate]                       
    from PDBCompr   
    where QuotationNo='JCS_G1415_008' and CompanyCode ='001' and QRevNo ='2'    
    and AddCmprId not in (select distinct AddCmprId from PDBCompr where QuotationNo='JCS_G1415_008' and CompanyCode ='001' and QRevNo ='3' ) 
    )  

    select * into #temp from cte 

    declare @cnt int , @loopCnt int=1 
    select @cnt =(select COUNT(*) from #temp) 

    while (@loopCnt<[email protected]) 
    begin 

    ;with cte2 as 
    (
    SELECT  
    sSLNO,             
    [CompanyCode] ,  
    [ProjectCode] ,   
    (select Max(PRevNo)+1 from PDBCompr) [PRevNo],  
    (select Max(CSlNo) +1 from PDBCompr)[CSlNo],  
    [ComprDescription] ,  
    [PID] ,  
    [RatingCode] ,  
    [Rating] ,  
    [StdSystems] ,  
    [BoosterSystems] ,  
    [GCUSystems] ,  
    [KOFSystems] ,  
    [HeaterSystems] ,  
    [OtherSystems] ,  
    [Comments] ,  
    [Currency1] ,  
    [UnitPrice1] ,  
    [Currency2] ,  
    [ExchRate2] ,  
    [UnitPrice2] ,  
    [Currency3],  
    [ExchRate3] ,  
    [UnitPrice3] ,  
    [CreateId] ,  
    [CreateDate] ,  
    [UpdateId] ,  
    [UpdateDate]                       
     from #temp where [email protected] 
    )  

    select * into PDBCompr from cte2 
    set @loopCnt= @loopCnt+1 
    drop table #temp 
     end 

適切な解決策を見つけるために私を助けてください。あなたは再びテーブル「PDBCompr」を作っているが、上記のコードでは、あなたがこのテーブルからレコードを選択している事前

答えて

0

のおかげで、このラインでCTE2

からPDBComprに選択*それはそのが既に存在していること。

あなたは、このテーブルにレコードを挿入したい場合ので、あなたは以下のようなあなたのクエリを変更する必要があります。

CTE2

から選択* PDBComprに挿入
関連する問題