Click here to Skip to main content
15,895,772 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All ,

I have a scenario where I need to update 2 tables in one update statement using joins. Can anybody help me out with this.

Below is the sample scenario.

SQL
DROP TABLE B
DROP TABLE D


CREATE TABLE B
(EMPCODE VARCHAR(20), SRNO INT, SALARY NUMERIC, Remarks varchar(100))

CREATE TABLE D
(EMPCODE VARCHAR(20), SRNO INT, SALARY NUMERIC, Remarks varchar(100))


INSERT INTO B
VALUES(1, 3, 17000,'')
INSERT INTO B
VALUES(1, 1, 15000,'')
INSERT INTO B
VALUES(1, 2, 16000,'')
INSERT INTO B
VALUES(2, 1, 15000,'')
INSERT INTO B
VALUES(2, 2, 16000,'')

INSERT INTO D
VALUES(1, 3, 17,'AAAA')
INSERT INTO D
VALUES(1, 1, 15,'bbbb')
INSERT INTO D
VALUES(1, 2, 16,'vvvv')
INSERT INTO D
VALUES(2, 1, 15,'dddd')
INSERT INTO D
VALUES(2, 2, 16,'hhhh')


SELECT * FROM B
SELECT * FROM D


SELECT *
FROM B
INNER JOIN D ON B.EMPCODE = D.EMPCODE AND B.SRNO = D.SRNO


UPDATE D
SET D.SALARY = B.SALARY--, B.SALARY = D.SALARY
FROM B
INNER JOIN D ON B.EMPCODE = D.EMPCODE AND B.SRNO = D.SRNO



Remarks of table D should be updated in table B and
Salary of Table B should be updated in Table D


Can anybody help me out with this.

Regards,
Gopal
Posted

1 solution

You cannot do that, you can only update one table at the time.

You can however use a transaction[^] so that you ensure both tables are update at the same time.
SQL
BEGIN TRAN T1

	-- Update Remarks
	UPDATE D
	SET D.Remarks = B.Remarks
	FROM D
	INNER JOIN B ON B.EMPCODE = D.EMPCODE AND B.SRNO = D.SRNO

	-- Update SALARY
	UPDATE B
	SET B.SALARY= D.SALARY
	FROM B
	INNER JOIN D ON D.EMPCODE = B.EMPCODE AND D.SRNO = B.SRNO

COMMIT TRAN T1
 
Share this answer
 
Comments
RaviRanjanKr 16-Oct-11 2:42am    
Correct, My 5+

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900