使用Oracle(或DB2,HSQLDB),我可以表达这样的事情:
MERGE INTO [target_table]
USING (SELECT 1 FROM dual)
ON [target_table.id = 5]
WHEN MATCHED THEN UPDATE ...
WHEN NOT MATCHED THEN INSERT ...
这只会检查id = 5
中是否已存在target_table
的记录。如果有,则记录更新,如果没有,则插入。这与MySQL更简洁的
INSERT INTO [target_table] ...
ON DUPLICATE KEY UPDATE ...
我如何在SQL Server中执行此操作?根据文档,[table_source]
必须是以下任何一个:
<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
显然,SQL Server没有DUAL
表,但也不允许使用SELECT
语句。我可以将[table_source]
作为什么?
N.B:我发现我可以创建一个虚拟视图
CREATE VIEW dummy (one) AS SELECT 1;
并将其作为[table_source]
提供。但是我想省略DDL语句只是为了能够执行这个MERGE
语句
答案 0 :(得分:6)
参见MERGE - 查看示例“C.使用MERGE通过使用派生源表对目标表执行UPDATE和INSERT操作”使用VALUES
(又名Table Value Constructor }):
MERGE INTO Target
USING (VALUES (1))
AS Source (Number)
...
快乐的编码。