数据打横(表A单独列a)
表 A
列 a
值 北京
上海
杭州
得到结果值:
列 a
值 北京,上海,杭州
因为是sql2000,不能用for xml,求可以解决方法
[解决办法]
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-17 16:03:15
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
--Dec 28 2012 20:23:12
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([a] varchar(4))
insert [A]
select '北京' union all
select '上海' union all
select '杭州'
--------------开始查询--------------------------
if object_id('F_Str') is not null
drop function F_Str
go
create function F_Str(@Col1 VARCHAR(200))
returns nvarchar(100)
as
begin
declare @S nvarchar(100)
select @S=isnull(@S+',','')+A from A --where A=@Col1
return @S
end
go
Select distinct a=dbo.F_Str(a) from A
go
/*
a
----------------------------------------------------------------------------------------------------
北京,上海,杭州
*/
create table #tb (col varchar(800))
insert into #tb
select '北京' union all
select '上海' union all
select '杭州'
declare @values varchar(800)
select @values = ISNULL(@values ,'')+','+COL from #tb
select STUFF (@values ,1,1,'')
drop table #tb
if object_id('[A]') is not null drop table [A]
go
create table [A]([a] varchar(4))
insert [A]
select '北京' union all
select '上海' union all
select '杭州'
--方法2. 函数,效率较高
if exists(select * from sysobjects where name = 'fn_mergeSTR')
drop function fn_mergeSTR
go
create function dbo.fn_mergeSTR(@v varchar(100),
@split varchar(10)) --分隔符
returns varchar(300)
as
begin
declare @str varchar(300);
set @str = '';
--这里的code改为需要合并的字段
select @str = @str +@split + [a]
from a
--where id = @id
set @str = stuff(@str,1,1,'')
return @str --返回值
end
go
select distinct dbo.fn_mergeSTR(a,',')
from a
/*
北京,上海,杭州
*/