3

我想要一个存储过程,它将行插入到一个表中(从另一个表的选择查询中检索),并且对于每个新插入的行获取它的标识并使用标识更新原始表

伪代码-

records = select id,city,state,country from USER where name=@name

for each record in records  // for each rows selected
   insert into LOCATION(city,state,country) values(@record.city,@record.state,@record.country); //inserts a value into LOCATION table
   @id = SCOPE_IDENTITY(); // gets the identity of the newly inserted row
   update USER set LocationId=@id where Id=@record.id //updates the new id back to old table's column
end

这是一个数据迁移任务,我们希望将 LOCATION 从 USER 表中分离出来

提前感谢您为此线程付出的时间和精力。

4

1 回答 1

5

你可以这样做:

DECLARE @InsertedValues TABLE (ID INT, City VARCHAR(50), State VARCHAR(50), Country VARCHAR(50))

INSERT INTO dbo.Location(City, State, Country)
  OUTPUT Inserted.ID, Inserted.City, Inserted.State, Inserted.Country INTO @InsertedValues(ID, City, State, Country)
    SELECT City, State, Country
    FROM dbo.YourSourceTable

有了这个,您现在在表变量中拥有插入的值 -包括新定义的标识值,@InsertedValues您现在可以根据需要更新源表。

UPDATE dbo.YourSourceTable
SET 
   Col1 = iv.Col1,
   Col2 = iv.Col2,  -- etc. - do whatever you nee to do here!
FROM @InsertedValues iv
WHERE  .........  -- here, you need some condition to link the inserted values to the original table

这根本不需要任何游标或任何其他混乱的 RBAR(逐行)处理 - 一切都很好地基于集合并且尽可能快。

OUTPUT在 MSDN SQL Server 联机丛书中了解有关该子句的更多信息- 您也可以OUTPUT在插入、更新甚至删除语句中使用该子句!

于 2013-01-26T18:08:44.757 回答