读书人

求一条sql查询语句?(!)

发布时间: 2012-01-03 22:16:06 作者: rapoo

求一条sql查询语句?(在线等!急急急)
主表a有两个字段sn , name;从表id ,sn ,Question;主表每天记录在从表中有多条记录相对应以sn 关联,我要的结果是每个sn 对应的Question都用逗号分隔显示。
sn Question
100 aaaa,bbbb,cccc
101 rrrr,eeeee,ddddd

[解决办法]
create table table1
(
sn int
)

create table table2
(
sn int,
questtion varchar(100)
)

insert into table1 values(100)
insert into table1 values(101)

insert into table2 values(100, 'aaa ')
insert into table2 values(100, 'bbb ')
insert into table2 values(100, 'ccc ')
insert into table2 values(101, 'rrr ')
insert into table2 values(101, 'eee ')
insert into table2 values(101, 'ddd ')

alter function myFunction(@sn int)
returns varchar(8000)
as
begin
declare @rtValue varchar(8000)
set @rtValue = ' '
select @rtValue = @rtValue +questtion + ', ' from table2 where sn=@sn
return @rtValue
end

select sn,dbo.myFunction(sn) from table1
[解决办法]
@sbqcel(活死人)

耶,建个函数不错,学到老,还以为要用游标呢,

只是,好像 return 之前要判断是否需要去掉最后一个 ,

IF LEN(@rtValue) > 0
SET @rtValue = LEFT(@rtValue, LEN(@rtValue) - 1)

读书人网 >asp.net

热点推荐