简体   繁体   中英

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

I have two tables, 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM