只用一条查询语句,select语句。
能否做一个查询,查询得到的结果是将一个字符字段的所有值串加到一起。
如:
表b1中,字段a1的5条记录分别是"a1"、"a2"、"a3"、"a5",查询结果得到“a1a2a3a5”

解决方案 »

  1.   

    一条查询没可能完成这样的功能,需要使用自定义函数。SQL不是万能的,不要指望SQL能完成用户的任何要求。
      

  2.   

    --??
    declare @test table
    (
    a varchar(20)
    )
    insert into @test
    select 'a1' union all
    select 'a2' union all
    select 'a3' union all
    select 'a4' union all
    select 'a5'declare @b varchar(20)
    select @b=''
    select @b=@b+a from @test
    select @b/*
    a1a2a3a4a5or you can use a function if you need group it
    */
      

  3.   

    use pubs
    if exists(select * from sysobjects where name='ta') drop table ta
    if exists(select * from sysobjects where name='tb') drop table tb
    gocreate table ta(pid int ,name char(10))
    insert ta select 1,'aa'
    create table tb(pid int,cid int)
    insert tb select 1,2
    union all select 1,5
    union all select 1,6select * from ta
    select * from tb
    goCREATE FUNCTION getStr(@pid int)
    returns varchar(100)
    as
    begin
    declare @strAll varchar(100)
    set @strAll=''
    select @strAll=@strAll+','+cast(cid as varchar(10)) from tb where pid=@pid
    return stuff(@strAll,1,1,'')
    end
    GOselect a.pid,[name],dbo.getstr(b.pid) 
    from ta a inner join tb b on a.pid=b.pid
    order by a.piddrop function getStr
    drop table ta,tb
      

  4.   

    上面数据演示的结果:pid         name       
    ----------- ---------- 
    1           aa        (所影响的行数为 1 行)pid         cid         
    ----------- ----------- 
    1           2
    1           5
    1           6(所影响的行数为 3 行)--结果--
    pid         name                                                                                                            
    ----------- ---------- ---------------------------------------------------------------------------------------------------- 
    1           aa         2,5,6
    1           aa         2,5,6
    1           aa         2,5,6(所影响的行数为 3 行)