表结构:
CREATE TABLE ATEST
(ID INTEGER,
NAME VARCHAR(256),
CODE INTEGER,
NAME2 VARCHAR(256)
)
CREATE TABLE BTEST
(ID INTEGER,
CODE INTEGER
)
CREATE TABLE CTEST
(ID INTEGER,
NAME VARCHAR(256),
NAME2 VARCHAR(256)
)
SQL语句:
一张表更新另一张表的字段:
update atest
set atest.name=(select ctest.name from ctest where atest.id = ctest.id)
where atest.id in (select ctest.id from ctest);
两张表关联更新另一张表的字段:
update atest
set (name,name2) = (SELECT CASE WHEN CTEST.NAME IS NULL THEN ATEST.NAME ELSE CTEST.NAME END, CASE WHEN CTEST.NAME2 IS NULL THEN ATEST.NAME2 ELSE CTEST.NAME2 END FROM BTEST LEFT JOIN CTEST on BTEST.ID = CTEST.ID WHERE atest.CODE = BTEST.CODE)
WHERE atest.CODE IN (SELECT BTEST.CODE FROM BTEST);
另外一个: http://blog.csdn.net/Bobwu/archive/2009/01/13/3768636.aspx
1.
declare
cursor t1 is select * from tablename;
begin
for rec in t1 loop
update tablename t set t.detail=rec.jieshao where t.objectid=rec.objid;
end loop;
end;
2.
update student set (name,id )=
(select name ,id from (select student.rowid rd,student1.name,student1.id from student1,student where student1.int_id =student.int_id) tmp
where student.rowid=tmp.rd);
commit;
3.
update test_a a set (a.name,a.age)=
(select b.name,b.age from test_b b where a.id = b.id) where exists
(select * from test_b c where c.id=a.id)
4.
UPDATE t_A SET Djrq=
(
SELECT djrq FROM t_B WHERE t_A.ID = T_B.ID
WHERE ROWNUM = 1
)
WHERE t_A.ID IN
(
SELECT ID FROM t_B WHERE jwh='XX村'
)
5.
update tbl1 a
set (a.col1, a.col2) = (select b.col1, b.col2
from tbl2 b
where a.key = b.key)
where a.key in(select key from tbl2)
MERGE INTO test1 a
USING all_objects b
ON (a.object_id = b.object_id)
WHEN MATCHED THEN
UPDATE SET a.status = b.status
WHEN NOT MATCHED THEN
INSERT (object_id, status)
VALUES (b.object_id, b.status);
update account
set firstname = (select max( firstname) from account where userid = 'ACID')
where userid = 'j2ee'
这是一个经典的问题,太多的理论不说了,我直接举个例子吧。
两张表T_USER(用户信息表),T_NAME_MAP(新老姓名映射表)
T_USER的字段:USER_ID,USER_NAME,USER_INFO;
T_NAME_MAP的字段:USER_ID,NEW_NAME;
具体语句:
UPDATE T_USER A SET A.USER_NAME = (SELECT B.NEW_NAME FROM T_NAME_MAP B WHERE A.USET_ID = B.USER_ID)
WHERE EXISTS (SELECT 1 FROM T_NAME_MAP C WHERE A.USER_ID = C.USER_ID );
特别提醒:
1、如果T_USER表中的一个USER_ID在T_NAME_MAP 表中存在两条以上的记录,则该语句会报错。因为Oracle是无法辨别你要“更新”哪一条的。当然,从纯技术的角度来看,这种情况也是可以处理的,你可以在B.NEW_NAME 上加一个函数,如MAX(B.NEW_NAME ).
2、WHERE EXISTS 语句绝对不可以省略,有了这个子句,才能实现“一对一”的批量更新,否则会报错“返回多行”了。
以上,希望可以对你有所帮助,共同提高