SQL如果匹配更新,如果不匹配则插入

时间:2014-01-26 18:45:06

标签: sql sql-server vb.net sql-server-2008

请帮助这一个...... 我正在尝试在VB中实现这个SQL代码,代码适用于更新但不适用于插入...

merge into anamneza a
using (select ana_id from anamneza where ana_id = 2) e 
on (a.ana_id = e.ana_id)
when matched then 
update set a.ana_kupanje = 'da' 
when not matched then
insert (ana_rb,ana_id,ana_kupanje,ana_kosa,ana_brijanje,ana_zubi,ana_nokti,ana_odjeca,ana_koza,ana_dek_rizik,ana_dek_rizik_gdje,ana_dek_postojeci,ana_dek_post_gdje,ana_pokretnost,ana_kolica,ana_pomagala,azurirao,datumazur)
values (1,1,'da','da','da','da','da','da','da','da','da','da','da','da','da','da','veki',getdate());

首先我在SQLQuery中编写并执行它并且它说 (0行(s)受影响)

但是,当我插入该行并且它具有id = 1并且更改那个选择它与ana_id = 1匹配时它表示(1行受影响);

为什么insert语句不起作用?

1 个答案:

答案 0 :(得分:1)

根据Using SQL Server MERGE command with same source & target table的建议,将MERGE语句的第2行替换为:

using (
    select 1 as ana_rb, 1 as ana_id,
           'da' as ana_kupanje, 'da' as ana_kosa, 'da' as ana_brijanje,
           'da' as ana_zubi, 'da' as ana_nokti, 'da' as ana_odjeca,
           'da' as ana_koza, 'da' as ana_dek_rizik, 'da' as ana_dek_rizik_gdje,
           'da' as ana_dek_postojeci, 'da' as ana_dek_post_gdje,
           'da' as ana_pokretnost, 'da' as ana_kolica, 'da' as ana_pomagala,
           'veki' as azurirao, getdate() as datumazur
) e

注意:确保这些值与INSERT部分中的值相匹配!