首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

请诸位大神帮忙解答

2013-12-26 
请各位大神帮忙解答。假设有A表B表codenamecodename1a1aaa2b3ccc3c5eee4d5e现在我想参照B表将A表更新为code

请各位大神帮忙解答。
假设有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

热点排行