I am trying to insert rows from table A back into table A, keeping the old and new columns.
Here is my basic example:
t_course_media
course_media_id (PK, int, not null) -- identity column
course_id (int, not null)
media_id (int, null),
...
t_media
media_id (PK, int, not null), -- this is the identity column
...
I was asked to copy course materials from 3 courses to one existing course. The trick in the existing course will require a new media_id so that each course has unique t_media child strings. How to save the new media_id from the insert so that I can insert the correct t_course_media lines associated with the new t_media lines that I just inserted into t_media?
MERGE OUTPUT. , , , . , media_id 1 ( xxxxx t_media). , - http://sqlblog.com/blogs/jamie_thomson/archive/2010/01/06/merge-and-output-the-swiss-army-knife-of-t-sql.aspx
DECLARE @source TABLE (
[id] INT PRIMARY KEY,
[name] VARCHAR(10)
);
INSERT @source VALUES(1000,'Harold'),(2000,'Madge');
DECLARE @destination TABLE (
[id] INT PRIMARY KEY IDENTITY(1,1),
NAME VARCHAR(10)
);
MERGE @destination
USING (SELECT [id], [name] FROM @source) AS [source]
ON (1=0)
WHEN NOT MATCHED THEN
INSERT (name)
VALUES (source.Name)
OUTPUT INSERTED.id AS NEWID,[source].[id] AS OldId,INSERTED.name;
NewID OldID name
1 1000 Harold
2 2000 Madge
, t_media media_id, ? , .