2012-09-10 99 views
2
declare @cid int 

set @cid=(select ISNULL(MAX(cid),0)+1 from CustInfo) 
insert into CustInfo(CID,CTypeId,CustNo,Regdate, 
        DOB,CCertID,CCertNo,CompId,PostedBy,PostedOn) 
(select @cid,1,0,'2012-9-10', 
     dob,ccertid,ccertno,0,null,null 
from updateCust3) 

我已經使用上面的代碼將表updateCust3中的值插入到表UpdateCustInfo中。 在這種情況下,每次插入時CID字段應該加1。我已經使用了上面的代碼,但cid似乎沒有增加,所以錯誤是主鍵的重複值。那麼我該如何增加cid的價值呢?由於表屬性的更改是不允許的,我不能使用標識屬性。從一個字段中的表中插入值到另一個表中的字段應該遞增

+1

有你沒有使用標識列任何理由使用時避免錯誤? – codingbiz

+0

表中的更改是不允許的所以我必須手動增加CId。 –

+3

如果兩個用戶同時執行代碼,他們可能會在'@ cid'中以相同的值結束並導致主鍵違例。您應該使用標識列。 –

回答

1

試試這個:

declare @cid int 

set @cid=(select ISNULL(MAX(cid),0)+1 from CustInfo) 
insert into CustInfo(CID,CTypeId,CustNo,Regdate, 
        DOB,CCertID,CCertNo,CompId,PostedBy,PostedOn) 
select @cid+row_number() over (order by (select 0)),1,0,'2012-9-10', 
     dob,ccertid,ccertno,0,null,null 
from updateCust3) 

編輯:作爲MikaelEriksson在評論中提到,這有風險,如果用戶試圖同時更新表,就會報錯了..

1

已經使用臨時表來演示。這是一個更好的工作方式由多個用戶

DECLARE @Table TABLE    
     (    
      CTypeId INT identity (1,1) 
      ,CustNo int 
      ,DOB datetime   
     ,Regdate datetime 
     ,CCertID int 
       ,CCertNo int 
     ,CompId int 
    ,PostedBy varchar(100) 
    ,PostedOn datetime 
     )  

      INSERT @Table  
      select 1,0,'2012-9-10', 
      dob,ccertid,ccertno,0,null,null 
    from updateCust3 
相關問題