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
d_sales = t.ytd_sales + s.qty
FROM titles t, sales s
WHERE t.title_id = s.title_id
d_date = (SELECT d_date) FROM sales)
exists的用法若要使上例合法,请从列名中删除别名 t 或使⽤本⾝的表名。
1.
UPDATE titles
SET ytd_sales = t.ytd_sales + s.qty
FROM titles t, sales s
WHERE t.title_id = s.title_id
d_date = (SELECT d_date) FROM sales)
2.
UPDATE titles
d_sales = t.ytd_sales + s.qty
FROM titles t, sales s
WHERE t.title_id = s.title_id
d_date = (SELECT d_date) FROM sales)
EXAMPLE
update item_master i al_ma= ( select l_ma) from base_complex b de=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 )

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。