插入记录和每个运行更新语句的存储过程

san*_*hat 3 sql-server stored-procedures sql-server-2005

我想有一个存储过程,它将行插入一个表(从另一个表中的select查询中检索),并为每个新插入的行获取其标识并使用标识更新原始表

伪代码 -

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
Run Code Online (Sandbox Code Playgroud)

这是一个数据迁移任务,我们希望将LOCATION与USER表隔离

提前感谢您为此主题花费的时间和精力.

mar*_*c_s 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
Run Code Online (Sandbox Code Playgroud)

有了这个,您现在可以在表变量中插入值 - 包括新定义的标识值 - @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
Run Code Online (Sandbox Code Playgroud)

这根本不需要任何游标或任何其他凌乱的RBAR(逐行激动行)处理 - 一切都很好地基于设置,并且尽可能快.

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