合并语句中的IF NOT EXISTS是什么意思?

5
当主键匹配且没有处于活动状态 '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    |
+-------+-------------+--------+

我希望这样更清晰明了。
编辑:算了,不可能的,我刚刚收到了这个错误信息:MERGE语句的'WHEN MATCHED'子句中不允许使用INSERT类型的操作。

1
这不是合并的工作方式。考虑使用传统的IF。 - Toby
提供表结构、示例数据和期望的最终结果将有助于理解您的问题并提供答案。 - Mikael Eriksson
我在编辑帖子时遇到了一些麻烦,但现在有一些示例数据。 - R2D2
1个回答

6
如果我理解正确,需要插入从@T2中不在@T1中的行,其中Active = 'y'
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的行也将被插入。如果您不想这样,也就是说,您只想在@T2中存在与代码匹配但Active = 'n'的行时才将行插入@T1,则可以使用以下方法。

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

谢谢!你的第二个脚本就是我需要的。只是你使用select的地方不是必需的,所以我把它去掉了,现在它按照我想要的方式工作了 =) - R2D2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接