Sql server 复制插入记录的每个标识

Sql server 复制插入记录的每个标识,sql-server,sql-server-2005,Sql Server,Sql Server 2005,我有两张桌子 第一: Table: TBL#Sell SellId ClientId ProductId 1 3 3 5 4 6 第二: Table: TBL#Sell2 SellId ClientId ProductId 现在我想把第一个表的每条记录复制到第二个表。 第二个

我有两张桌子 第一:

Table:     TBL#Sell

   SellId    ClientId    ProductId
                1           3
                3           5
                4            6
第二:

 Table: TBL#Sell2

    SellId      ClientId       ProductId
现在我想把第一个表的每条记录复制到第二个表。 第二个表中的“SellId”列(Sell2.SellId)是自动递增的(Identity)

对于任何插入,TBL#Sell2.SellId将设置新标识,我必须将标识存储在TBL#Sell1.SellId中
清楚吗?
解决办法是什么,请。 谢谢

我想将TBL#Sell2.SellId存储在TBL#Sell.SellId中

您可以使用触发器:


我认为你有更多的方法来完成这项任务

您可以编写一个存储过程,将表1中的每个记录写入表2,然后更新表1,从中获取标识值

或者另一种方法是,如果ClientId/ProductId是一个键,则执行插入操作,然后使用类似的内容进行更新:

insert into TBL#Sell2
select SellId, ClientId, ProductId from TBL#Sell

upadte TBL#Sell
set TBL#Sell.SellId = TBL#Sell2.SellId
from TBL#Sell T1 join TBL#Sell2 T2
on T1.ClientId = T2.ClientId and T1.ProductId  = T2.ProductId 
编辑将@@Identity替换为SCOPE\u Identity

TBL\Sell2
为空,您基本上只想给
TBL\Sell
中的每一行指定一个数字。您无需使用
TBL#Sell2
即可完成此操作

添加临时标识列,将值移动到
SellId
,删除临时列

alter table TBL#Sell add SellId_tmp int not null identity
go
update TBL#Sell set SellId = SellId_tmp
go
alter table TBL#Sell drop column SellId_tmp
另一种方法是使用带有行号()的CTE


查看联机丛书中的OUTPUT子句

不清楚要将TBL存储在何处。SellIdI要将TBL#Sell2.SellId存储在TBL#Sell中。SellIdI是TBL中唯一的ClientId和ProductId的组合,Sell?lo siento。不************************复制行之前TBL#Sell2是空的吗?复制之前TBLSell中的所有SellId都是空的吗?clientid/productid不是第一个表中的键?永远不要使用@identity,也不要教人们使用它。它并不总是返回正确的值,并且会破坏您的数据完整性。对,我用scope_identity替换了它,它应该是正确的使用方法
;with cte as
(
  select *,
    row_number() over(order by (select(1))) as rn
  from TBL#Sell
) 
update cte set
  SellId = rn