I have a table Items which should have a corresponding record in the table LanguageText. The ID (Identity) of LanguageText is registered in the Items.LanguageTextId field in my Items table.
What I want to accomplish is a merge between LanguageText and Items for all records with null in Items.LanguageTextId and insert the itemname / text of these Item records in LanguageText plus update the LanguageTextId with the ID value from the newly inserted LanguageText record (SCOPE_IDENTITY()?)
The insert works fine:
MERGE [dbo].[LanguageText] AS target
USING (SELECT [Items].* from [dbo].Items ) AS source
ON (TARGET.Id = SOURCE.LanguageTextId)
WHEN NOT MATCHED By Target THEN
INSERT
([Text])
VALUES
(source.[ItemName]);
end
But I don’t know how to update my items.Languagetextid, can I do something with:
OUTPUT $action, INSERTED.ID ?
Or is there a better way to have this done??
Thanks in advance,
Mike
You can do this with a merge..output to a table variable followed by an update.
SQL Fiddle
MS SQL Server 2008 Schema Setup:
Query 1:
Results:
Query 2:
Results:
Query 3:
Results: