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

急查询有关问题

2012-04-05 
急急急急急急急急急急急急急急急急!!!!!查询问题大家过年好SQL code现在我有两个表一个是人员表,一个是项

急急急急急急急急急急急急急急急急!!!!!查询问题
大家过年好

SQL code
现在我有两个表一个是人员表,一个是项目表我想将两个字段中的信息进行转换人员表id    姓名1     张三2     李四项目表id  项目名称  人员1     a       1,2,2     b        1,我想要这样的结果项目名称   人员a          张三,李四b          张三不知道我表述的清楚不清楚,谢谢了


[解决办法]
SQL code
if object_id('[人员表]') is not null drop table [人员表]gocreate table [人员表]([id] int,[姓名] varchar(4))insert [人员表]select 1,'张三' union allselect 2,'李四'goif object_id('[项目表]') is not null drop table [项目表]gocreate table [项目表]([id] int,[项目名称] varchar(1),[人员] varchar(4))insert [项目表]select 1,'a','1,2,' union allselect 2,'b','1,'go--sql2005及以上版本;with t1 as(select b.项目名称,a.姓名from 人员表 ajoin 项目表 b on charindex(','+ltrim(a.id)+',',','+b.人员)>0)select 项目名称,人员=stuff((select ','+姓名 from t1 where 项目名称=t.项目名称 for xml path('')),1,1,'')from t1 tgroup by 项目名称/**项目名称 人员---- --------------------a    张三,李四b    张三(2 行受影响)**/--sql2000用函数create function f_name(@id varchar(10))returns varchar(1000)asbegin  declare @str varchar(1000)  set @str=''  select @str=@str+','+姓名 from 人员表 where charindex(','+ltrim(id)+',',','+@id)>0  return stuff(@str,1,1,'')endgo select 项目名称,人员=dbo.f_name(人员) from 项目表/**项目名称 人员---- -----------------a    张三,李四b    张三(2 行受影响)**/
[解决办法]
/*
现在我有两个表一个是人员表,一个是项目表
我想将两个字段中的信息进行转换
人员表
id 姓名
1 张三
2 李四
项目表
id 项目名称 人员
1 a 1,2,
2 b 1,
我想要这样的结果
项目名称 人员
a 张三,李四
b 张三
不知道我表述的清楚不清楚,谢谢了
*/
go
if OBJECT_ID('t1') is not null
drop table t1
go
create table t1(
id varchar(5),
pname varchar(10)
)
go
insert t1
select '1','张三' union all
select '2','李四'
go
if OBJECT_ID('t2') is not null
drop table t2
go
create table t2(
id varchar(5),
iname varchar(5),
pname varchar(100)
)
insert t2
select '1','a','1,2,' union all
select '2','b','1,'

go
if OBJECT_ID('fun_tracy') is not null
drop function fun_tracy
go
create function fun_tracy(@id varchar(10))
returns varchar(100)
as
begin
declare @str varchar(100)
set @str=''
select @str=@str+','+pname from t1 
where charindex(','+ltrim(id)+',',','+@id)>0
return stuff(@str,1,1,'')
end


--调用函数:
select iname as 项目名称,项目人员=dbo.fun_tracy(pname) from t2

/*
你要的结果:
项目名称项目人员
a张三,李四
b张三
*/

热点排行
Bad Request.