一、当用一个表中的数据来更新另一个表中的数据,T-SQL提供多种写法(下面列出了二种),但建议用第一种写法,虽然传统,但结构清晰。
并且要注意,当用一个表中的数据来更新另一个表中的数据时,二个表一定要有关联!
1.
update t1
set t1.c2 = t2.c2
fro m t2
where t1.c1 = t2.c1
2.
Update t1
set t1.c2 = t2.c2
fro m 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)
看结果应该是使用Union ALL合并查询结果,而不是表关联
示例
select * from 表A
union all
select * from 表B
表A和表B的列格式必须一致,且数量一致
update hwsp
set hwshl = 0
from hwsp , spkfk b
where hw='HWI00000001' and hwshl>0 and hwsp.spid=b.spid and tongym like'%2'
update hwsp a,spkfk b set a.hwshl=o where b.hw='HWI00000001' and b.hwshl>0 and b.tongym like'%2' and a.spid=b.spid