本文介绍了T-SQL:在OUTPUT子句中插入INSERT原始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表 Items(ItemID,名称等) ,其中 ItemID 是自动生成的身份

I have a table Items (ItemID, Name, ...) where ItemID is auto-generated identity

我想从同一表上的select中向该表中添加行.并将OriginalItemID和NewlyGeneratedID之间的引用保存到表变量中.

I want to add rows into this table FROM select on this same table.AND save into table variable the references between OriginalItemID and NewlyGeneratedID.

所以我希望它看起来如下:

So I want it to look like the following:

DECLARE @ID2ID TABLE (OldItemID INT, NewItemID INT);

INSERT INTO Items OUTPUT Items.ItemID, INSERTED.ItemID INTO @ID2ID
SELECT * FROM Items WHERE Name = 'Cat';

Items.ItemID显然在这里不起作用.是否有一种解决方法可以使OUTPUT从SELECT语句中获取原始ItemID?

BUT Items.ItemID obviously does not work here. Is there a workaround to make OUTPUT take original ItemID from the SELECT statement?

推荐答案

如果您使用的是SQL Server 2008+,则可以使用 MERGE 来获取当前ID和新ID.该技术在此问题中进行了描述.

If you are on SQL Server 2008+, you can use MERGE for getting both the current and the new ID. The technique is described in this question.

对于您的示例,该语句可能看起来像这样:

For your example the statement might look like this:

MERGE INTO
  Items AS t
USING
  (
    SELECT *
    FROM Items
    WHERE Name = 'Cat'
  ) AS s
ON
  0 = 1
WHEN NOT MATCHED BY TARGET THEN
  INSERT (target_column_list) VALUES (source_column_list)
OUTPUT
  S.ItemID, INSERTED.ItemID INTO @ID2ID (OldItemID, NewItemID)
;

这篇关于T-SQL:在OUTPUT子句中插入INSERT原始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 10:36