合并为没有行

时间:2015-06-19 12:26:34

标签: sql-server tsql merge

有没有办法使用该指令:

MERGE INTO MySchema.MyTable AS Target
USING (VALUES
........
)

没有任何东西而不是点?通常你有一些像(firstValue,SecondValue,...,LastValue)的列表,你想要合并的每一行,但我希望能够写入没有行的指令,以便DELETE MERGE的一部分删除所有行。

这是因为我使用的是一个自动创建MERGE指令的存储过程,但有时我开始的表是空的。

当然我试过了:

MERGE INTO MySchema.MyTable AS Target USING (VALUES) 

但不接受。

示例:

MERGE INTO [dbo].[MyTable] AS Target
USING (VALUES (1,'Attivo') ,(2,'Disabilitato') ,(3,'Bloccato') ) AS Source ([IDMyField],[MyField]) ON (Target.[IDMyField] = Source.[IDMyField])
WHEN MATCHED AND ( NULLIF(Source.[MyField], Target.[MyField]) IS NOT NULL OR NULLIF(Target.[MyField], Source.[MyField]) IS NOT NULL)
THEN UPDATE SET [MyField] = Source.[MyField]
WHEN NOT MATCHED BY TARGET
THEN INSERT([IDMyField],[MyField]) VALUES(Source.[IDMyField],Source.[MyField]) 
WHEN NOT MATCHED BY SOURCE
THEN DELETE; 

2 个答案:

答案 0 :(得分:4)

可行的解决方案是:

USING (SELECT * FROM MyTable WHERE 1 = 0) 

答案 1 :(得分:1)

如果您正在生成内部查询,并且外部查询在预定义的ID字段上匹配,则以下内容将起作用:

MERGE INTO tester AS Target
USING (

select null as test1 --generate select null, alias as your id field
) as SOURCE on target.test1 = source.test1
WHEN NOT MATCHED BY SOURCE 
    THEN DELETE;

对于你的特例:

MERGE INTO table1 AS Target
USING (

values(null)
) as SOURCE(id) on target.id = source.id
WHEN NOT MATCHED BY SOURCE 
    THEN DELETE;