--示例数据
if object_id('tb')is not null
drop table tb
go
create table tb(col1 varchar(1),col2 int)
insert into tb select 'a',1
union all
select 'a',2
union all
select 'b',1
union all
select 'b',2
union all
select 'b',3
select * from tb--------------------函数合并法*/
create function dbo.f_str(@col1 varchar(100))
returns varchar(100)
as 
begin
declare @s varchar(100)
set @s =''
select @s=@s+','+cast(col2 as varchar(100))
  from tb
where col1=@col1
return (stuff(@s,1,1,''))
end
go
-- drop function dbo.f_str

解决方案 »

  1.   

    ---测试数据---
    if object_id('[主表]') is not null drop table [主表]
    go
    create table [主表]([pid] int,[name] varchar(5))
    insert [主表]
    select 1,'test1' union all
    select 2,'test2'
    if object_id('[从表]') is not null drop table [从表]
    go
    create table [从表]([pid] int,[color] varchar(5))
    insert [从表]
    select 1,'white' union all
    select 1,'black' union all
    select 1,'rouge' union all
    select 2,'white'
     
    ---创建字符连接函数---
    if object_id('F_Str') is not null
        drop function F_Str
    go
    create function F_Str(@pid int)
    returns nvarchar(100)
    as
    begin
        declare @S nvarchar(100)
        select @S=isnull(@S+',','')+[color] from (select distinct [color] from  [从表] where pid=@pid) t
        return @S
    end---查询---
    select distinct
      a.pid,
      b.[name],
      dbo.F_Str(a.pid) as [color]
    from [从表] a
    left join [主表] b
    on a.pid=b.pid
    ---结果---
    pid         name  color                             
    ----------- ----- ---------------------------------
    1           test1 black,rouge,white
    2           test2 white(所影响的行数为 2 行)