日期:2014-05-18  浏览次数:20444 次

请教个行列转换问题,谢谢
表a

编号         内容(注意:这个ntext类型的)
1               xxxx
1               yyyyy
2               aaa
4               ccccc
4               ddddd
4                 eeeee

.....

希望得到   ====》

编号         内容(注意:这个ntext类型的)
1                 xxxx$$yyyyy
2                 aaa
4                 ccccc$ddddd%eeeee

.....

ntext类型   怎么弄啊?
谢谢。



------解决方案--------------------
先参考一个:
create table tbltest(编号 int,内容 varchar(100))
go
insert into tbltest
select 1, 'xxxx ' union all
select 1, 'yyyyy ' union all
select 2, 'aaa ' union all
select 4, 'ccccc ' union all
select 4, 'ddddd ' union all
select 4, 'eeeee '
go

--写一个聚合函数:
create function dbo.fn_Merge(@F1 int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r= ' '
select @r=@r+ ', '+内容 from tbltest where 编号=@F1
return stuff(@r,1,1, ' ')
end
go

-- 调用函数
select 编号, dbo.fn_Merge(编号) as 内容
from tbltest
group by 编号
go

--删除测试数据
drop table tbltest
drop function fn_Merge

--查看结果
/*
编号 内容
1 xxxx,yyyyy
2 aaa
4 ccccc,ddddd,eeeee
*/
------解决方案--------------------
USE tempdb
GO

CREATE TABLE A(
编号 int, 内容 ntext)
INSERT A
select 1, 'xxxx ' union all
select 1, 'yyyyy ' union all
select 2, 'aaa ' union all
select 4, 'ccccc ' union all
select 4, 'ddddd ' union all
select 4, 'eeeee '
GO

-- 处理
SELECT
pkid = IDENTITY(int,1,1),
flag = 0,
编号, 内容
INTO #
FROM A

DECLARE @pkid int, @编号 int, @编号1 int,
@p1 binary(16), @p2 binary(16),
@SP nvarchar(10)

SET @SP = '分隔符 '

DECLARE tb CURSOR LOCAL
FOR
SELECT pkid, 编号, TEXTPTR(内容)
FROM #
ORDER BY 编号, pkid
OPEN tb
FETCH tb INTO @pkid, @编号, @p2
WHILE @@FETCH_STATUS = 0
BEGIN
IF @编号1 = @编号
BEGIN
UPDATETEXT #.内容 @p1 NULL 0 @SP
UPDATETEXT #.内容 @p1 NULL 0 #.内容 @p2
END
ELSE
BEGIN
UPDATE # SET
flag = 1,
@p1 = @p2,
@编号1 = @编号
WHERE pkid = @pkid
END
FETCH tb INTO @pkid, @编号, @p2
END
CLOSE tb
DEALLOCATE tb

SELECT 编号, 内容
FROM #
WHERE flag = 1
GO

DROP TABLE #, A