当前位置: 代码迷 >> Sql Server >> 请诸位大神帮忙解答
  详细解决方案

请诸位大神帮忙解答

热度:52   发布时间:2016-04-24 19:29:31.0
请各位大神帮忙解答。
假设有A表                   B表
code  name                  code  name    
1     a                              1     aaa   
2     b                              3     ccc
3     c                              5     eee
4     d
5     e
现在我想参照B表将A表更新为
code  name                  
1     aaa           
2     b                           
3     ccc                          
4     d
5     eee
请各位大神帮帮忙,用一条SQL语句搞定。

------解决方案--------------------
update a
set name = b.name
from b
inner join code = b.code
------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2013-12-24 07:42:52
-- Version:
--      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
-- Dec 28 2012 20:23:12 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go 
create table [A]([code] int,[name] varchar(3))
insert [A]
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d' union all
select 5,'e'
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go 
create table [B]([code] int,[name] varchar(3))
insert [B]
select 1,'aaa' union all
select 3,'ccc' union all
select 5,'eee'
--------------开始查询--------------------------

--查询
select ISNULL(a.code,b.code)code,ISNULL(b.NAME,a.NAME)name
from [A] LEFT JOIN [B] ON a.code=b.code

--更新
UPDATE a
SET a.NAME=isnull(b.NAME,a.NAME)
from [A] LEFT JOIN [B] ON a.code=b.code
SELECT * FROM a

----------------结果----------------------------
/* 

code        name
----------- ----
1           aaa
2           b
3           ccc
4           d
5           eee
*/

------解决方案--------------------

UPDATE a SET NAME=b.NAME
from a
JOIN b ON a.code=b.code

------解决方案--------------------
试试这个:
update a
set name = b.name
from b
where a.code = b.code

------解决方案--------------------
update a set name=b.name
from a
JOIN b ON a.code=b.code
  相关解决方案