SQL 語句多張表UPDATE語法


多張表UPDATE用法

sql 語句多張表UPDATE用法
一、當用一個表中的數據來更新另一個表中的數據,T-SQL提供多種寫法(下面列出了二種),但建議用第一種寫法,雖然傳統,但結構清晰。
並且要注意,當用一個表中的數據來更新另一個表中的數據時,二個表一定要有關聯!
1.
update t1 set t1.c2 = t2.c2
from t2
where t1.c1 = t2.c1
2.
Update t1 set t1.c2 = t2.c2
from t1 inner join t2 on t1.c1 = t2.c1
二、FROM 子句中指定的表的別名不能作為 SET column_name 子句中被修改字段的限定符使用。
UPDATE titles
SET t.ytd_sales = t.ytd_sales + s.qty
FROM titles t, sales s
WHERE t.title_id = s.title_id
AND s.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

若要使上例合法,請從列名中刪除別名 t 或使用本身的表名。
1.
UPDATE titles
SET ytd_sales = t.ytd_sales + s.qty
FROM titles t, sales s
WHERE t.title_id = s.title_id
AND s.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

2.
UPDATE titles
SET titles.ytd_sales = t.ytd_sales + s.qty
FROM titles t, sales s
WHERE t.title_id = s.title_id
AND s.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

EXAMPLE
update item_master i set i.contral_ma= ( select max(b.control_ma) from base_complex b where b.code=i.hs_code );

更新一列:
update mytab a set name=(select b.name from goal b where b.id=a.id)
where exists (select 1 from goal b where b.id=a.id);
更新多列:
update mytab a
set (name,address)=(select b.name,b.address
from goal b
where b.id=a.id)
where exists (select 1
from goal b
where b.id=a.id )
特別是要注意exists后面的語句:)這會讓目標行不至於為NULL

更新update多個關聯表的SQL寫法:
update customers a
set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)
update 超過2個值
update customers a
set (city_name,customer_type)=(select b.city_name,b.customer_type
from tmp_cust_city b
where b.customer_id=a.customer_id)
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM