-4

How can we update two tables with single sql query?

Suppose I have two tables

1. Employee

empid  empname     salary
00001   Vijay      100000
00002   Alex       200000
00003   Jennifer   300000


2. Institute

regno    State        Country
123ab    Texas          USA
231nf    California     USA

So how can we update both tables lets say I want to update "salary" field of "empid" 00001 of "Employee" table and the "State" field of "regno" 123ab of Institute table.

Marc B
  • 356,200
  • 43
  • 426
  • 500
Vijay Chauhan
  • 397
  • 3
  • 5
  • 9

4 Answers4

3
  1. if it's related data, you can probably can do a JOIN.
  2. if it's not, you are probably looking not for 1 query, but 1 transaction
  3. if you still need it to be 1 call, define a procedure
Wrikken
  • 69,272
  • 8
  • 97
  • 136
  • thanks for the information but mate can we use some other way to find the solution apart from Transaction and Procedures ? – Vijay Chauhan Oct 17 '13 at 19:03
  • 1
    @VijayChauhan By now you should be aware that there's no way to do it in a single SQL instruction... that's what transactions are for – Barranka Oct 17 '13 at 19:07
  • 3
    Honestly, trying to avoid transactions or procedures, having unrelated data, and still insisting on a single query, smells a **lot** like asking for instructions on how to do an SQL-injection attack after having found a security flaw. It may not be it, but at the very least is see no _valid_ use for the requirements any other way. – Wrikken Oct 17 '13 at 19:17
1
BEGIN TRANSACTION
query1;
query2;
COMMIT
Mihai
  • 26,325
  • 7
  • 66
  • 81
0

You could create a stored procedure which updates Employee and then updates Institute so then your single query would be:

exec spUpdateEmployeeTableAndInstituteTable
Jack Marchetti
  • 15,536
  • 14
  • 81
  • 117
0

It actually can be done in one query:

UPDATE Employee e, Institute i
SET e.salary = <new salary>,
    i.state = <new state>
WHERE e.empid = '00001'
AND i.regno = '123ab'
Barmar
  • 741,623
  • 53
  • 500
  • 612