I have a situation where I need to insert data from table1 to table2. Before insert check if a certain row already exist in the table2.
Conditions are if:
1) the values of id and ahccs are same in both the table, then don’t do anything.
2) the value of id are same but ahccs are different, then set flag =’z’ and insert the same id with the new ahccs value.
I am using SQLSERVER 2008 R2. How could I achieve this?
I might need something like this.
DECLARE @table1 TABLE
(id int not null, ahccs int not null, info varchar(25), flag varchar(2))
DECLARE @table2 TABLE
(id int not null, ahccs int not null, info varchar(25), flag varchar(2))
INSERT INTO @table1
VALUES(1, 1223, 'et', 'X')
INSERT INTO @table1
VALUES(2, 321, 'et', 'X')
INSERT INTO @table1
VALUES(3, 134, 'et', 'X' )
INSERT INTO @table1
VALUES(4, 168, 'et', 'X' )
INSERT INTO @table1
VALUES(5, 123, 'et', 'X' )
INSERT INTO @table2
VALUES(1, 1223, 'dt', 'y' )
INSERT INTO @table2
VALUES(2, 456, 'dt', 'y' )
INSERT INTO @table2
VALUES(3, 123, 'dt', 'y' )
INSERT INTO @table2
VALUES(4, 193, 'dt', 'y' )
--SELECT * FROM @table1
SELECT * FROM @table2
MERGE
INTO @table2 t2
USING @table1 t1
ON t2.id = t1.id
WHEN MATCHED AND t2.ahccs != t1.ahccs THEN
UPDATE
SET flag = 'z'
INSERT VALUES (t2.id, t1.ahccs, t1.info, 'l');
The two issues I am having are:
1) Merge doesn’t support multiple steps, I believe.
2) Update is not allowed in WHEN NOT MATCHED case.
Please advise.
Thank You.
I think I understand the requirements now. You want to update records in table2 where the id matches but ahccs does not, setting the flag to ‘z’. Additionally, for these mismatches, a new row should be inserted into table2 with the same id but the ahccs from table1, and a flag of ‘l’.