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, if it does then just update col2, col4 of the row. If it doesn't exist then insert a new row.
I am using SQLSERVER 2008 R2. How could I achieve this?
The situation has changed a bit now. I 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 or t2.ahccs = t1.ahccs
WHEN NOT MATCHED THEN
UPDATE
SET flag = 'z'
INSERT VALUES (100, 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.