简体   繁体   中英

Update Table's rows based on another table'rows

I have 2 tables SQL Server(Tab1,Tab2)

Tab1 has

col1
col2 
col3 

Tab2 has

col11
col22 
col33

I want to copy data form

col1 into col11, and col2 into col22.

if col3 equal to col33.

How can i do that?

Just Join the tables Based on col3 = col33 and Update the other columns.

UPDATE T2
    SET
       col11 = T1.col1,
       col22 = T1.col2
    FROM Tab1 T1
       INNER JOIN Tab2 T2
          ON T2.col33 = T1.col3

You have to just select column values from Tab2 and insert in Tab1 as below:

INSERT INTO Tab2 (col11,col22,col33) 
SELECT T1.col1,T1.col2,T1.col3 
FROM Tab1 T1
WHERE T1.col3 EXISTS IN(SELECT col33 FROM Tab2 WHERE col33=T1.col3)

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