开发者

Update Multiple Tables at a Time - SQL Server/T-SQL

开发者 https://www.devze.com 2022-12-31 19:00 出处:网络
I have two tables开发者_如何学C, Customer and CustomerPhone. Single record in Customer can have multiple CustomerPhone records. As you see in the image below, Phone and Fax resides in CustomerPhone t

I have two tables开发者_如何学C, Customer and CustomerPhone.

Single record in Customer can have multiple CustomerPhone records. As you see in the image below, Phone and Fax resides in CustomerPhone table whereas the rest of the fields resides in Customer table. If user want to edits a customer record, obviously i will have to update the record in Customer table and at least two records from CustomerPhone (Phone and Fax).

http://img714.imageshack.us/img714/9417/snapshotapp.jpg http://img714.imageshack.us/img714/9417/snapshotapp.jpg

I could write two update statements, one Update customerPhone and the second update Customer table. Is there a better solution?


The risk in a case like this is that the one update succeeds but the other fails for some reason (a network cable is unplugged, power failure, whatever) which would leave your data in the database incorrect.

You can overcome this in 2 ways.

  1. Do the 2 separate updates, but enclose them in a single transaction
  2. Implement a customer update stored procedure which updates both tables for you, in either an implicit or explicit transaction.

There is no way in SQL to update multiple tables in a single statement, but you can of course have multiple statements in the same command.

The second option above may be problematic for you as you can have many phone numbers for a customer and it would be limiting, so I would suggest running the separate updates, but do it in a transaction.


Several ways about this one:

  • Write two update statements wrapped in a transaction (TransactionScope object)
  • Write a stored procedure that does the update and use the SQL Transaction management
  • Both
0

精彩评论

暂无评论...
验证码 换一张
取 消