简体   繁体   English

使用OUTPUT子句从SELECT INSERT语句中检索原始和新标识映射

[英]Retrieve original and new identities mapping from SELECT INSERT statement using OUTPUT clause

I have a table with two columns: 我有一个有两列的表:

CREATE TABLE MyTable(
  Id int IDENTITY(1,1) NOT NULL,
  Name nvarchar(100) NOT NULL);

I want to duplicate the data using SELECT INSERT statement: 我想使用SELECT INSERT语句复制数据:

INSERT INTO MyTable (Name)
SELECT Name FROM MyTable

and here is the trickey part - I want to retrieve a mapping table between the original identity and the new identity: 这里是三角形部分 - 我想检索原始身份和新身份之间的映射表:

DECLARE @idsMap TABLE (OriginalId int, NewId int)

I know I suppose to use the OUTPUT clause , but for some reason it doesn't work: 我知道我想使用OUTPUT子句 ,但由于某种原因它不起作用:

INSERT INTO MyTable (Name)
OUTPUT t.Id, INSERTED.Id INTO @idsMap (OriginalId, NewId)
SELECT Name FROM MyTable t
-- Returns error The multi-part identifier "t.Id" could not be bound.

Related questions: 相关问题:
can SQL insert using select return multiple identities? SQL插入使用select返回多个身份?
Possible to insert with a Table Parameter, and also retrieve identity values? 可以插入表参数,还可以检索标识值?

It can be achieved using MERGE INTO and OUTPUT : 它可以使用MERGE INTOOUTPUT

MERGE INTO MyTable AS tgt
USING MyTable AS src ON 1=0 --Never match
WHEN NOT MATCHED THEN
INSERT (Name)
VALUES (src.Name)
OUTPUT
    src.Id,
    inserted.Id
INTO @idsMap;

How about just adding a new column to MyTable? 如何向MyTable添加新列? You can keep it around as long as you need to analysis or whatever. 只要你需要分析或其他什么,你可以保留它。 I have to say it seems a bit off to me to create a copy of the table but that is up to you to decide. 我不得不说创建一个表的副本对我来说似乎有点不对,但这取决于你自己决定。

Something like this might work for you. 这样的事可能适合你。

alter table MyTable
add OldID int null;

INSERT INTO MyTable (Name, OldID)
SELECT Name , Id
FROM MyTable t

select * from MyTable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM