日期:2014-05-17  浏览次数:20584 次

求两个关联后的结果
a表
id   name  age
1     张三  18
2     李四  19
b表
id    uid   girlfreadname
1      1       翠花
2      1       凤姐
3      2       石榴姐
4      2       芙蓉姐姐

要求查询结果
张三  18    翠花,凤姐
李四  19     石榴姐,芙蓉姐姐

a表的id和b表的uid关联。

------解决方案--------------------
SQL2000示例:

if not object_id('Tab') is null
    drop table Tab
Go
Create table Tab([Col1] int,[Col2] nvarchar(1))
Insert Tab
select 1,N'a' union all
select 1,N'b' union all
select 1,N'c' union all
select 2,N'd' union all
select 2,N'e' union all
select 3,N'f'
Go
 
合并表:
 
SQL2000用函数:
 
go
if object_id('F_Str') is not null
    drop function F_Str
go
create function F_Str(@Col1 int)
returns nvarchar(100)
as
begin
    declare @S nvarchar(100)
    select @S=isnull(@S+',','')+Col2 from Tab where Col1=@Col1
    return @S
end
go
Select distinct Col1,Col2=dbo.F_Str(Col1) from Tab