日期:2014-05-18 浏览次数:20480 次
SELECT 序号,姓名 AS 承担任务人员编号,任务名称 FROM 人员表 AS A,任务表 AS B WHERE A.序号 = B.承担任务人员编号
------解决方案--------------------
/*问题描述 tba ID classid name 1 1,2,3 西服 2 2,3 中山装 3 1,3 名裤 tbb id classname 1 衣服 2 上衣 3 裤子 我得的结果是 id classname name 1 衣服,上衣,裤子 西服 2 上衣,裤子 中山装 3 衣服,裤子 名裤 */ ----------------------------------------------------- --sql server 2000中的写法 create table tba(ID int,classid varchar(20),name varchar(10)) insert into tba values(1,'1,2,3','西服') insert into tba values(2,'2,3' ,'中山装') insert into tba values(3,'1,3' ,'名裤') create table tbb(ID varchar(10), classname varchar(10)) insert into tbb values('1','衣服') insert into tbb values('2','上衣') insert into tbb values('3','裤子') go --第1种方法,创建函数来显示 create function f_hb(@id varchar(10)) returns varchar(1000) as begin declare @str varchar(1000) set @str='' select @str=@str+','+[classname] from tbb where charindex(','+cast(id as varchar)+',',','+@id+',')>0 return stuff(@str,1,1,'') end go select id,classid=dbo.f_hb(classid),name from tba drop function f_hb /* id classid name ----------- ------------- ---------- 1 衣服,上衣,裤子 西服 2 上衣,裤子 中山装 3 衣服,裤子 名裤 (所影响的行数为 3 行) */ --第2种方法.update while(exists (select * from tba,tbb where charindex(tbb.id,tba.classid) >0)) update tba set classid= replace(classid,tbb.id,tbb.classname) from tbb where charindex(tbb.id,tba.classid)>0 select * from tba /* ID classid name ----------- -------------------- ---------- 1 衣服,上衣,裤子 西服 2 上衣,裤子 中山装 3 衣服,裤子 名裤 (所影响的行数为 3 行) */ drop table tba,tbb ------------------------------------ --sql server 2005中先分解tba中的classid,然后再合并classname create table tba(ID int,classid varchar(20),name varchar(10)) insert into tba values(1,'1,2,3','西服') insert into tba values(2,'2,3' ,'中山装') insert into tba values(3,'1,3' ,'名裤') create table tbb(ID varchar(10), classname varchar(10)) insert into tbb values('1','衣服') insert into tbb values('2','上衣') insert into tbb values('3','裤子') go SELECT id , classname , name FROM ( SELECT DISTINCT id , name FROM (select tbc.id , tbc.name , tbb.classname from ( SELECT A.id , A.name , B.classid FROM(SELECT id , name , [classid] = CONVERT(xml,'<root><v>' + REPLACE([classid], ',', '</v><v>') + '</v></root>') FROM tba)A OUTER APPLY(SELECT classid = N.v.value('.', 'varchar(100)') FROM A.[classid].nodes('/root/v') N(v))B ) tbc , tbb where tbc.classid = tbb.id ) T )A OUTER APPLY ( SELECT [classname]= STUFF(REPLACE(REPLACE(( SELECT classname FROM (select tbc.id , tbc.name , tbb.classname from ( SELECT A.id , A.name , B.classid FROM(SELECT id , name , [classid] = CONVERT(xml,'<root><v>' + REPLACE([classid], ',', '</v><v>') + '</v></root>') FROM tba)A OUTER APPLY(SELECT classid = N.v.value('.', 'varchar(100)') FROM A.[classid].nodes('/root/v') N(v))B ) tbc , tbb where tbc.classid = tbb.id ) N WHERE id = A.id and name = A.name FOR XML AUTO), '<N classname="', ','), '"/>', ''), 1, 1, '') )N order by id drop table tba,tbb /* id classname name ----