如果没有出现在合并声明中?

时间:2011-11-22 10:14:58

标签: sql sql-server merge

我想执行以下操作,当主键匹配时,如果没有活动的行' Y'插入记录。这可能吗?

我试过了:

-- Merge statement
MERGE INTO table1 AS DST
USING table2 AS SRC
ON (SRC.Code = DST.Code)

 --Existing records updated if data changes
WHEN MATCHED 
AND IF NOT EXISTS (WHERE active='Y' FROM table1 )

THEN
INSERT INTO table1 (colum)
SELECT value

+-------+-------------+--------+
| Code  | description | Active |
+-------+-------------+--------+
| AB    | just        |    |
|       |  something  | No     |
+-------+-------------+--------+

只有当没有相同代码的活动记录时,我才想插入记录。新记录看起来像这样

+-------+-------------+--------+
| Code  | description | Active |
+-------+-------------+--------+
| AB    | something   |    |
|       | else        | YES    |
+-------+-------------+--------+

我希望这更清楚

编辑:没关系它不可能,我刚收到此错误消息: 类型' INSERT' “匹配时”不允许使用' MERGE声明的条款。

1 个答案:

答案 0 :(得分:5)

如果我理解正确,请插入@T2@T1所在的行Active = 'y'。{/ p>

declare @T1 table
(
  Code char(2),
  Descr varchar(10),
  Active char(1)
)

declare @T2 table
(
  Code char(2),
  Descr varchar(10)
)

insert into @T1 values
('1', 'Desc 1', 'y'),
('2', 'Desc 2', 'n')

insert into @T2 values
('1', 'Desc 1'),
('2', 'Desc 2'),
('3', 'Desc 3')

merge @T1 as D
using @T2 as S
on D.Code = S.Code and 
   D.Active = 'y'
when not matched then
  insert (Code, Descr, Active) 
    values (Code, Descr, 'y');

select *
from @T1

结果:

Code Descr      Active
---- ---------- ------
1    Desc 1     y
2    Desc 2     n
2    Desc 2     y
3    Desc 3     y

还将插入代码3的行。如果您不希望这样,意味着您只想向@T1插入一行,如果@T2中已存在一行且代码匹配但Active = 'n',则您可以使用此行代替

merge @T1 as D
using (select Code,
              Descr
       from @T2
       where Code in (select Code 
                      from @T1 
                      where Active = 'n')) as S
on D.Code = S.Code and 
   D.Active = 'y'
when not matched then
  insert (Code, Descr, Active) 
    values (Code, Descr, 'y');

结果:

Code Descr      Active
---- ---------- ------
1    Desc 1     y
2    Desc 2     n
2    Desc 2     y