|
一、MS SQL Server 多表关联更新
sql server提供了update的from 子句,可以将要更新的表与其它的数据源连接起来。虽然只能对一个表进行更新,但是通过将要更新的表与其它的数据源连接起来,就可以在update的表达式 中引用要更新的表以外的其它数据。
一般形式:
update A SET 字段1=B表字段表达式, 字段2=B表字段表达式 from B WHERE 逻辑表达式
例如:
UPDATE dbo.Table2
SET dbo.Table2.ColB = dbo.Table2.ColB + dbo.Table1.ColB
FROM dbo.Table2
INNER JOIN dbo.Table1
ON (dbo.Table2.ColA = dbo.Table1.ColA);
实际更新的操作是在要更新的表上进行的,而不是在from子句所形成的新的结果集上进行的
二、Oracle 多表关联更新
Oracle没有update from语法,可以通过两种实现方式:
update A
SET 字段1=(select 字段表达式 from B WHERE ...),
字段2=(select 字段表达式 from B WHERE ...)
WHERE 逻辑表达式
UPDATE多个字段两种写法:
写法一:
UPDATE table_1 a
SET col_x1 = (SELECT b.col_y1, b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m),
col_x2 = (SELECT b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m)
WHERE EXISTS (SELECT * FROM table_2 b WHERE b.col_n = a.col_m)
或
UPDATE table_1 a
SET col_x1 = (SELECT b.col_y1, b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m),
col_x2 = (SELECT b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m)
WHERE a.col_m=(SELECT b.col_n FROM table_2 b WHERE b.col_n = a.col_m)
写法二:
UPDATE table_1 a
SET (col_x1, col_x2) = (SELECT b.col_y1, b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m)
WHERE EXISTS (SELECT * FROM table_2 b WHERE b.col_n = a.col_m);
或
UPDATE table_1 a
SET (col_x1, col_x2) = (SELECT b.col_y1, b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m)
WHERE a.col_m=(SELECT b.col_n FROM table_2 b WHERE b.col_n = a.col_m)
更新单个记录
UPDATE PUR_PO K SET K.AMOUNT_HASACCEPT_UA=AMOUNT_HASACCEPT_UA+
(SELECT TOTAL_AMOUNT FROM PUR_ACCEPT WHERE FORM_NO=1021 AND ACCEPT_TYPE_VALUE=1 AND STATUS='UA') G
WHERE K.FORM_NO=G.PO_NO
更新多个记录
Oracle写法1
Merge into PUR_PO A
Using (SELECT TOTAL_AMOUNT,PO_NO FROM PUR_ACCEPT WHERE FORM_NO=1021 AND ACCEPT_TYPE_VALUE=1) B
on (A.FORM_NO=B.PO_NO )
when Matched then Update set A.a=A.a-B.TOTAL_AMOUNT,A.b=A.b+b.TOTAL_AMOUNT
Oracle写法2
UPDATE PUR_PO p1 set(a, b)=(select p1.a - p2.total_amount, p1.b + p2.total_amount from PUR_ACCEPT p2 where p1.form_no=p2.po_no and p2.FORM_NO=1021 AND p2.ACCEPT_TYPE_VALUE=1)
where exists(select * from PUR_ACCEPT p2 where p1.form_no=p2.po_no and p2.FORM_NO=1021 AND p2.ACCEPT_TYPE_VALUE=1)
|
|