读书人

一条更新语句!该如何处理

发布时间: 2013-12-26 00:35:35 作者: rapoo

一条更新语句!
表A


select '1','PP,*' union all
select '1','*' union all
select '1','PP' union all
select '2','uu,*' union all
select '2','uu' union all
select '2','*' union all
select '3','' union all
select '3','*'

表B

select '1','PP,*'
select '2','UU,*'
select '3','*'

根据表B的类型更新表A A与B的第一个字段关连 结果:
1 PP,*
1 PP,*
1 PP,*
2 uu,*
2 uu,*
2 uu,*
3 *
3 *
[解决办法]
--select '1' id,'PP,*'NAME INTO #A
-- union all
--select '1','*' union all
--select '1','PP' union all
--select '2','uu,*' union all
--select '2','uu' union all
--select '2','*' union all
--select '3','' union all
--select '3','*'



--select '1' id,'PP,*' NAME INTO #B
--union all
--select '2','UU,*'
--union all
--select '3','*'

SELECT * FROM #a
SELECT * FROM #b

UPDATE #a
SET #a.name=#b.name
FROM #b
WHERE #a.id=#b.id

/*
id NAME
---- ----
1 PP,*
1 PP,*
1 PP,*
2 UU,*
2 UU,*
2 UU,*
3 *
3 *
*/

[解决办法]

select '1' id,'PP,*' descr INTO #a union all
select '1','*' union all
select '1','PP' union all
select '2','uu,*' union all
select '2','uu' union all
select '2','*' union all
select '3','' union all
select '3','*'

select '1' id,'PP,*' descr INTO #b union all
select '2','UU,*' union all
select '3','*'

UPDATE a SET descr=b.descr
from #a a
JOIN #b b ON a.id=b.id

SELECT * FROM #a

[解决办法]

create table a(id varchar(10),descr varchar(20))

insert into a
select '1' id,'PP,*' union all
select '1','*' union all
select '1','PP' union all
select '2','uu,*' union all
select '2','uu' union all
select '2','*' union all
select '3','' union all
select '3','*'

create table b(id varchar(10),descr varchar(20))

insert into b
select '1' id,'PP,*' descr union all
select '2','UU,*' union all
select '3','*'
go

--更新数据
UPDATE a
SET descr=b.descr
from b
where a.id=b.id


SELECT * FROM a
/*
iddescr
1PP,*
1PP,*
1PP,*
2UU,*
2UU,*
2UU,*
3*
3*
*/

读书人网 >SQL Server

热点推荐