我有一个名为data
的表格,列ip, report_date, group, value
。主键是ip
,report_date
和group
。
当表为空并且我运行下面的语句时,没有插入任何内容。我的陈述有什么问题?
当匹配时,记录按计划更新...
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);
答案 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)
我发现NULLs
在ON
语句的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 ...)