I want to create "UPDATE if exists else INSERT" statements for existing values in a table with the following pattern:
if exists (select 1 from TABLE_NAME where Ident_Column=Identifier )
update TABLE_NAME set
Column1=Value1,
Column2=Value2,
Column3=Value3,
...
where Ident_Column=Identifier
else
insert into TABLE_NAME ( Column1, Column2, Column3, ...)
select Value1, Value2, Value3, ...
go
I try to use the MSSQL Mangement Studio (2014) script generator, but I do not get the output as desired.
EDIT: The desired output IS the SQL statement, @Rusland K. & Nick.McDermaid . I want to use the script generator to generate this SQL code for each (or selected) rows of the table TABLE. Identifier is not a variable, its a value. If the value Identifier in Column Ident_Column exists, set the row accordingly (Value 1-n). If that Identifier is not found in any row, create a now row accordingly. @bmsqldev: This is the entire code (just replaced the real column/table names and the concrete values)
Actually I'm don't understand what caused the missunderstanding here. If you can tell, I'd be happy to learn.
EDIT2: I endet up writing a small script which converts the script output of MSSQL Mangement Studio according to this pattern, which took me about 2 hours.
MERGE. Or simply remove theIFand use the properWHEREstatements in theUPDATEandINSERTclauses. The speed will be the same as MERGE. You could also join the target table with either a source query or TVP to perform the MERGE/UPSERT for all rows at onceOUTPUTclauses though