I would like to merge a table bar
into another table foo
, and while doing so I have to assign a unique value to a column messagenr
. This is my attempt to do so (sql-server):
MERGE foo AS target
using bar AS source
ON target.message LIKE source.message
WHEN NOT matched BY target THEN
INSERT (messagenr,
language,
message)
VALUES ((SELECT Max(messagenr)
FROM foo)
+ 1,
'EN',
source.message);
Of course it is not working. I get the very same value for messagenr
for every new dataset inserted.
I cannot modify the table structure itself, so I have to work with the structure given.
How can I get a UNIQUE value for messagenr
in every new dataset in the target table?
Best Answer
Let me set up next example:
Since you can't increase
messagenr
value inside the transaction, and your MERGE statement only insert values, maybe you could use another approach.You can use a CTE or a subquery to enumerate the returned rows in this way:
Now you can insert new values using the previous query:
This is the final result:
dbfiddle here