【问题标题】:IF NOT EXISTS in Merge statement?IF NOT EXISTS 在 Merge 语句中?
【发布时间】:2012-01-03 17:43:16
【问题描述】:

当主键匹配并且没有带有活动“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”类型的操作。

【问题讨论】:

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

标签: sql sql-server merge


【解决方案1】:

如果我理解正确,请从@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 的地方才不需要,所以我把它省略了,它按照我想要的方式工作 =)
猜你喜欢
  • 2022-01-02
  • 1970-01-01
  • 2021-10-20
  • 2012-06-05
  • 2015-05-16
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多