题目是这样的:
比如我现在有两张表:
A、姓名 性别 学历 民族
01 06 15 35
08 05 20 43
B、代码 说明
01 小王
05 女
06 男
08 小红
15 大学
20 高中
35 回族
43 汉族现在,我想通过B表替换A表中相同代码的数据为B表中的说明,请问该怎替换?
结果应为:C、姓名 性别 学历 民族
小王 男 大学 回族
小红 女 高中 汉族大家帮帮忙呀!!!
比如我现在有两张表:
A、姓名 性别 学历 民族
01 06 15 35
08 05 20 43
B、代码 说明
01 小王
05 女
06 男
08 小红
15 大学
20 高中
35 回族
43 汉族现在,我想通过B表替换A表中相同代码的数据为B表中的说明,请问该怎替换?
结果应为:C、姓名 性别 学历 民族
小王 男 大学 回族
小红 女 高中 汉族大家帮帮忙呀!!!
insert into a select '01', '06', '15', '35'
union all select '08', '05', '20', '43'
create table b(代码 varchar(10), 说明 varchar(10))
insert into b select '01', '小王'
union all select '05', '女'
union all select '06', '男'
union all select '08', '小红'
union all select '15', '大学'
union all select '20', '高中'
union all select '35', '回族'
union all select '43', '汉族'update a set 姓名=(select 说明 from b where 代码=a.姓名),
性别=(select 说明 from b where 代码=a.性别),
学历=(select 说明 from b where 代码=a.学历),
民族=(select 说明 from b where 代码=a. 民族)
from a
姓名.说明 as 姓名,
性别.说明 as 性别,
学历.说明 as 学历,
民族.说明 as 民族
from
a
left join
b 姓名
on
a.姓名=姓名.代码
left join
b 性别
on
a.性别=性别.代码
left join
b 学历
on
a.学历=学历.代码
left join
b 民族
on
a.民族=民族.代码--看看你的设计是多么的麻烦
from a a,b b where a.姓名=b.代码 and a.性别=b.代码 and a.学历=b.代码 and a.民族=b.代码
(
姓名 varchar(10),
性别 varchar(10),
学历 varchar(10),
民族 varchar(10)
)
insert into tab1(姓名,性别,学历,民族) values('01','06','15','35')
insert into tab1(姓名,性别,学历,民族) values('08','05','20','43')if object_id('pubs..tab2') is not null
drop table tab2
go
create table tab2
(
代码 varchar(10),
说明 varchar(10)
)insert into tab2(代码,说明) values('01','小王')
insert into tab2(代码,说明) values('05','女')
insert into tab2(代码,说明) values('06','男')
insert into tab2(代码,说明) values('08','小红')
insert into tab2(代码,说明) values('15','大学')
insert into tab2(代码,说明) values('20','高中')
insert into tab2(代码,说明) values('35','回族')
insert into tab2(代码,说明) values('43','汉族')select id=identity(int,1,1) , tab2.说明 as 姓名 into #a from tab1,tab2 where tab1.姓名=tab2.代码
select id=identity(int,1,1) , tab2.说明 as 性别 into #b from tab1,tab2 where tab1.性别=tab2.代码
select id=identity(int,1,1) , tab2.说明 as 学历 into #c from tab1,tab2 where tab1.学历=tab2.代码
select id=identity(int,1,1) , tab2.说明 as 民族 into #d from tab1,tab2 where tab1.民族=tab2.代码
select a.姓名,b.性别,c.学历,d.民族 from #a a,#b b,#c c, #d d
where a.id = b.id and a.id = c.id and a.id = d.iddrop table tab1
drop table tab2
drop table #a
drop table #b
drop table #c
drop table #d--结果
姓名 性别 学历 民族
---------- ---------- ---------- ----------
小王 男 大学 回族
小红 女 高中 汉族(所影响的行数为 2 行)