由一个表里的数据更新另一个表里的数据



来源:http:
// hi.baidu.com / chaowei_yuwen / blog / item / e2078ecbabccc081c9176841.html

由一个表里的数据更新另一个表里的数据:
情况:
因为操作错误,导致库存里件号和货品不符合,用新提供的excel数据(很多,而且仅仅批号lot_no和货品prod_id)去更新原有数据。
做法:
建立临时表(用临时表导数据是一种技巧)
SQL:
update  inventory  set  prod_id =
(
select  prod_id  from  inventory_temp  where  inventory_temp.lot_no = inventory.lot_no
)
where   exists
(
select  lot_no  from  inventory_temp  where  inventory_temp.lot_no = inventory.lot_no
)
体会:
用一个表去更新另一个表
上边写法可以简写为:
update  a
set  a.name = ( select  b.name  from  a.id  =  b.id)
where  exsits ( select   1   from  a.id  =  b.id);
如果更新的是多个字段:
UPDATE  employees a
    
SET  department_id  =
        (
SELECT  department_id
            
FROM  departments
            
WHERE  location_id  =   ' 2100 ' ),
        (salary, commission_pct) 
=
        (
SELECT   1.1 * AVG (salary),  1.5 * AVG (commission_pct)
          
FROM  employees b
          
WHERE  a.department_id  =  b.department_id)
    
WHERE  department_id  IN
        (
SELECT  department_id
          
FROM  departments
          
WHERE  location_id  =   2900
              
OR  location_id  =   2700 );

-- -----------------------------------------

另外一个: 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)

保存备用

你可能感兴趣的:(数据)