Sybase: How do I concatenate rows in sybase column

▼魔方 西西 提交于 2019-12-01 12:13:04

This is the best way I know. Please do post if anyone knows a better solution:

I have named your table sal

DECLARE @id     INT
        , @max  INT
        , @dep  INT
        , @all  VARCHAR(255)

SELECT  @id = 1
        , @max = MAX(id)
FROM    sal

SELECT * INTO #tmp FROM sal

WHILE (1=1)
BEGIN

    SELECT  @dep = dept
    FROM    #tmp
    WHERE   id = @id

    IF @dep IS NULL
    BEGIN
        SELECT  @id = @id + 1

        IF @id > @max
            BREAK
        ELSE
            CONTINUE
    END

    UPDATE  #tmp
    SET     @all = @all + ',' + CONVERT(VARCHAR, id) 
    WHERE   dept = @dep

    --remove last comma
    select  @all = RIGHT(@all, LEN(@all)-1)

    DELETE  #tmp
    WHERE   dept = @dep

    -- selecting the output. insert into table if you want
    SELECT  @dep, @all

    SELECT  @dep   = NULL
            , @all = NULL

    SELECT  @id = @id + 1

    IF @id > @max
        BREAK

    -- fail safe
    IF @id > 100
        BREAK
END

drop table #tmp

I had similar problem and came up with the following solution:

select dept,list(id,',' order by dept) from TableName group by dept

Assuming TableName is the name of your table.

A bit simpler solution for those who want this to work for particular query:

DECLARE @res_csv  VARCHAR(10000)
BEGIN
    SELECT SomeIntField INTO #tmp FROM YourTblName WHERE 1=1 -- a hardcoded query
    UPDATE  #tmp
    SET     @res_csv = @res_csv + case when @res_csv is not NULL then ',' end + CONVERT(VARCHAR, SomeIntField) 
    drop table #tmp
    print @res_csv
END
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!