合并SQL Server中的字段

时间:2010-07-06 02:41:20

标签: sql-server sql-server-2005 sql-server-2000

如何在SQL Server 2000中组合行

2 个答案:

答案 0 :(得分:1)

您是否尝试在SQL Server 2000中使用FOR XML RAW

答案 1 :(得分:0)

您可以创建用户定义的函数来为每个ID值执行字符串连接。

create table t (id int,start varchar(100),finish varchar(100)) 
insert into t  
select 1,'Start_Main', '' union all  
select 1,'Start_Submain1', '' union all  
select 2,'Start_Main', '' union all  
select 2,'Start_Submain2', 'End_Submain2' union all  
select 2,'Start_Submain3', 'End_Submain3' union all 
select 2,'Start_Submain1', ''  union all 
select 2,'Start_Submain4', 'End_Submain4'   
Select * from t 
go

/* User Defined Function to perform string concatenation per ID */
create function udfStringConcat (@ID int)
returns varchar(500)
as
begin
    declare @x varchar(500)
    set @x = ''

    select @x = @x + t.start + ',' + case when t.finish <> '' then t.finish + ',' else t.finish end
        from t
        where t.id = @ID

    select @x = @x + 'End_Submain1,End_Main'

    return @x
end
go

select id, dbo.udfStringConcat(id)
    from t
    group by id
go

drop function udfStringConcat
drop table t
go