IF NOT EXISTING in the Merge statement?

I want to do the following when the primary keys match and there are no lines with active "Y" inserts. Is it possible?

I tried this:

-- 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     |
+-------+-------------+--------+

only if there is no active record with the same code, I want to insert a record. The new entry will look like this:

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

I hope this becomes clearer.

edit: Don’t pay attention to it, I just got this error message: An "INSERT" action is not allowed in the "WHEN MATCHED" clause of the MERGE statement.

+5
source share
1 answer

If you understand correctly, insert lines from @T2that are not already in @T1where 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

Result:

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
+5

All Articles