In this article, we will be discussing how to update column value with the column value of other table.
This is a very common requirement. Most often we will come across this situation.
Let's Create a table and insert sample data:
Here we are creating two tables.
CREATE TABLE UPDATETEST1 ( ID INT, VALUE NVARCHAR(250) )
INSERT INTO UPDATETEST1 VALUES (1,'ABC')
INSERT INTO UPDATETEST1 VALUES (2,'BCD')
INSERT INTO UPDATETEST1 VALUES (3,'CDE')
INSERT INTO UPDATETEST1 VALUES (4,'DEF')
CREATE TABLE UPDATETEST2 (ID INT, VALUE NVARCHAR(250))
INSERT INTO UPDATETEST2 VALUES (1,'ABC')
INSERT INTO UPDATETEST2 VALUES (2,'XYZ')
INSERT INTO UPDATETEST2 VALUES (3,'CDE')
INSERT INTO UPDATETEST2 VALUES (4,'DEF')
INSERT INTO UPDATETEST1 VALUES (1,'ABC')
INSERT INTO UPDATETEST1 VALUES (2,'BCD')
INSERT INTO UPDATETEST1 VALUES (3,'CDE')
INSERT INTO UPDATETEST1 VALUES (4,'DEF')
CREATE TABLE UPDATETEST2 (ID INT, VALUE NVARCHAR(250))
INSERT INTO UPDATETEST2 VALUES (1,'ABC')
INSERT INTO UPDATETEST2 VALUES (2,'XYZ')
INSERT INTO UPDATETEST2 VALUES (3,'CDE')
INSERT INTO UPDATETEST2 VALUES (4,'DEF')
Select table1:
SELECT * FROM UPDATETEST1
Select table2:
SELECT * FROM UPDATETEST2
In the above two tables ID 2 having two different values in the tables.
Now, let's see how to update the table UPDATETEST2 VALUE column with table UPDATETEST1 VALUE column based on the ID column condition.
Query 1: Using NON-ANSI Join
UPDATE A
SET A.VALUE = B.VALUE
FROM UPDATETEST2 A,
UPDATETEST1 B
WHERE A.ID = B.ID
AND A.VALUE <> B.VALUE
SET A.VALUE = B.VALUE
FROM UPDATETEST2 A,
UPDATETEST1 B
WHERE A.ID = B.ID
AND A.VALUE <> B.VALUE
Query 2: Using ANSI Join ( American National Standards Institute)
UPDATE A
SET A.VALUE = B.VALUE
FROM UPDATETEST2 A
INNER JOIN UPDATETEST1 B
ON A.ID = B.ID
WHERE A.VALUE <> B.VALUE
SET A.VALUE = B.VALUE
FROM UPDATETEST2 A
INNER JOIN UPDATETEST1 B
ON A.ID = B.ID
WHERE A.VALUE <> B.VALUE
Output post update:
Thank you for visiting the blog. hope you got the required information.
No comments:
Post a Comment