Possible Duplicate:
How to update two tables in one statement in SQL Server 2005?
I have two tables and need to update one table and take effect to the other table.
These two tables are linked by a relationship
t1.col1 PK , t2.col1 FK
t1 t2
_____________ _____________
|col1| col2| |col1 |col2 |
|----|------| |-----|-----|
|1 | a | | 1 | d |
|2 | b | | 2 | e |
|3 | c | | 3 | f |
|____|______| |_____|_____|
How I can update these two tables in one query in SQL Server 2008 ?
I want to do something like that
Update College
Inner Join Class ON College.CollegeId = Class.CollegeId
set College.CollegeId = '33333333-3333-3333-3333-333333333333',
Class.CollegeId = '33333333-3333-3333-3333-333333333333'
where
College.CollegeId = '071887ea-3c93-40ce-a112-3b849d352064'
but I get an error:
incorrect syntax near the keyword “Inner”
Whether you update 2 tables with one statement in one query on one connection or 2 tables with two statements in one query on one connection, it is the same thing really.
You can set parameters to pass to the script then you only have to send the value once and run the script once which will in turn only use one connection.
However, I am guessing the reason you want to do this simultaniously is because you can’t update college first without updating class because of the relationship? Trying to Update College.CollegeID will result in error because of the foreign key Class.CollegeID. The same applies visa versa. Class.CollegeID will not be updatable unless the Class.CollegeID you are updating to exists in College.CollegeID. In this case I will suggest the following:
This will update all your old college records with the new id and you wont have to worry. You might have to do something differently in your front end application to cater for this depending on what it is. Keeping it a stored procedure will allow you to exec it and everything will update to the parameters passed.