Passing column updates from one table to another table

Source: Internet
Author: User

Q: How do you update three columns in table A with three columns in table B in an UPDATE statement?

A: For this problem, you can use powerful relational algebra. The code in this page shows how to combine the FROM clause and join operation to achieve the purpose of updating the specified column with data in another table. When you design a relationship expression, you need to decide whether you want a single row to match multiple rows (one-to-many relationships), or multiple rows to match a single row in the joined table to update all rows (Many-to-many relationships).

In a one-to-many relationship, SQL Server always updates data with the last row it finds. However, you cannot control where the last row is located. On a multiprocessor computer, the query may be synchronized, and the last row of the same query may be in a different position. Therefore, Microsoft recommends that you do not use a one-to-many relationship as much as possible.

If the table to be updated is the same as the table in the FROM clause, and the FROM clause contains only one reference to the table, the alias may not be specified. If the table to be updated appears more than once in the FROM clause, only one reference to the table can omit the alias of the table, and all other references to the table must contain a table alias.

Use tempdb
Go
CREATE TABLE #t1 (c1 int not NULL, C2 char (5), C3 char (5),
C4 char (5))
Go
CREATE TABLE #t2 (c1 int not NULL, C2 char (5), C3 char (5),
C4 char (5))
Go


--Data assignment
INSERT #t1 VALUES (1, ' hello ', ' there ', ' Fred ')
INSERT #t2 VALUES (1, ' How ', ' are ', ' you? ')


--Update data
UPDATE #t1 SET #t1. C2 = #t2. c2, #t1. c3 = #t2. c3,
#t1. c4 = #t2. c4
From #t2
WHERE #t1. C1 = #t2. C1


--Check the results
SELECT * from #t1

-microsoft SQL Server Development team



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.