With Oracle (or DB2, HSQLDB), I can express things like this:
MERGE INTO [target_table]
USING (SELECT 1 FROM dual)
ON [target_table.id = 5]
WHEN MATCHED THEN UPDATE ...
WHEN NOT MATCHED THEN INSERT ...
This just checks if there is already a record with id = 5 in target_table. If there is, then the record is update, if there isn’t then it is inserted. This is roughly the same as MySQL’s more concise
INSERT INTO [target_table] ...
ON DUPLICATE KEY UPDATE ...
How can I do that in SQL Server? According to the documentation, the [table_source] needs to be any of these:
<table_source> ::=
{
table_or_view_name [ [ AS ] table_alias ] [ <tablesample_clause> ]
[ WITH ( table_hint [ [ , ]...n ] ) ]
| rowset_function [ [ AS ] table_alias ]
[ ( bulk_column_alias [ ,...n ] ) ]
| user_defined_function [ [ AS ] table_alias ]
| OPENXML <openxml_clause>
| derived_table [ AS ] table_alias [ ( column_alias [ ,...n ] ) ]
| <joined_table>
| <pivoted_table>
| <unpivoted_table>
}
http://msdn.microsoft.com/de-de/library/bb510625.aspx
Obviously, SQL Server does not have a DUAL table, but neither is a SELECT statement allowed. What can I put as [table_source] ?
N.B: I found out that I can create a dummy view
CREATE VIEW dummy (one) AS SELECT 1;
and supply that as the [table_source]. But I would like to omit DDL statements just to be able to execute this MERGE statement
See MERGE — look at the example “C. Using MERGE to perform UPDATE and INSERT operations on a target table by using a derived source table” which uses
VALUES(aka Table Value Constructor):Happy coding.