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的值呢?由于不允许更改表属性,因此我无法使用身份属性。
最佳答案
试试这个:
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 在评论中提到的,这存在风险,如果您的用户同时尝试更新表,则会出错..
关于sql - 在sql server 2008中将一个表中的值插入到另一个表中,其中一个字段应该递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12348740/