SQL Server MERGE,如果存在则更新else插入

时间:2012-03-15 12:45:36

标签: sql sql-server-2008 merge

我有一个名为data的表格,列ip, report_date, group, value。主键是ipreport_dategroup

当表为空并且我运行下面的语句时,没有插入任何内容。我的陈述有什么问题?

当匹配时,记录按计划更新...

MERGE bc_data2 AS Target
USING (SELECT ip, report_date, group, value FROM bc_data2 As b
WHERE b.ip = '1.1.1.2'
AND b.report_date = '2/29/2012'
AND b.group = 'EPO-Client-Update') AS Source
ON (Target.ip = Source.ip
AND Target.frequency = Source.frequency
AND Target.report_date = Source.report_date
AND Target.service = Source.service
AND Target.proxy_service = Source.proxy_service
AND Target.proxy = Source.proxy
AND Target.service_group = Source.service_group)
WHEN MATCHED THEN
    UPDATE SET Target.value = Target.value + 1
WHEN NOT MATCHED BY Target THEN
    INSERT (ip, report_date, group, value)
    VALUES ('1.1.1.2', '2/29/2012', 'EPO-Client-Update', 119437142);

2 个答案:

答案 0 :(得分:4)

您不添加任何行,因为您的using子句未返回任何行。将常量放在带有列别名的using子句中,并使用when not matched

中的字段

像这样的一些字段删除了简单性。

merge bc_data2 as T
using (select '1.1.1.2' as ip,
              '2012-02-29' as report_date,
              1194370142 as value) as S
on T.ip = S.ip and
   T.report_date = S.report_date
when matched then
  update set T.value = T.value + 1
when not matched then
  insert (ip, report_date, value) 
    values(ip, report_date, value);

答案 1 :(得分:0)

我发现NULLsON语句的MERGE子句中没有得到很好的比较。但是,将NULLs转换为空白是一种有效的解决方法。我会修改ON语句看起来像这样。

ON (ISNULL(Target.ip, '')           = ISNULL(Source.ip, '')
AND ISNULL(Target.frequency, '')    = ISNULL(Source.frequency, '')
AND ISNULL(Target.report_date, '')  = ISNULL(Source.report_date, '')
AND ...)