日期:2014-05-17  浏览次数:20639 次

表间的更新语句怎么写?
有两个表:
table1
  id    field2
  001       5
  002       7


table2
  id   field2  field3
  001    6       19
  002    10      34
  003    15      16


现在想实现这样的效果:
table1与table2两个表,关联字段是id,现在判断table1与table2中相同的id值,用table1表中的field2值来更新table2中的field2值,实现如下的效果:
  id   field2  field3
  001    5      19
  002    7      34
  003    15      16

------最佳解决方案--------------------
EXEC CS'
$table1
   id    field2
   001       5
   002       7
 

$table2
   id   field2  field3
   001    6       19
   002    10      34
   003    15      16
 
'

--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
GO
create table [table1]([id] varchar(3),[field2] int)
insert [table1]
select '001',5 union all
select '002',7
--> 测试数据:[table2]
if object_id('[table2]') is not null drop table [table2]
GO
create table [table2]([id] varchar(3),[field2] int,[field3] int)
insert [table2]
select '001',6,19 union all
select '002',10,34 union all
select '003',15,16

UPDATE t2 
     SET t2.field2 = t.field2
FROM table1 t INNER JOIN table2 t2 ON t.id=t2.id

SELECT * FROM table2 t

/*
id   field2      field3
---- ----------- -----------
001  5           19
002  7           34
003  15          16

(3 行受影响)

*/

drop table [table1]
drop table [table2]

------其他解决方案--------------------

with tb1(id,field2)
as(
 select '001',5 union all
 select '002',7
),
tb2(id,field2,field3)
as(
 select '001',6,19 union all
 select '002',10,34 union all
 select '003',15,16
)
select tb1.id,(case when tb1.field2<tb2.field2 then tb1.field2 else tb2.field2 end) field2,field3
from tb1,tb2 where tb1.id=tb2.id
union select * from tb2 where tb2.id not in (select id from tb1)