日期:2014-05-17  浏览次数:20464 次

求语句 字符串连接
sql server 2000

比如有如下表:

t(mobile,content)
123  qwer
234  qwer
345  qwer
456  asdf
567  asdf
678  sdfg
789  wert


现欲得结果:按 content 分组,然后将 mobile 用 "," 拼接
如:123,234,345  qwer
    456,567,678  asdf
    789          wert

由于 sql server 版本为 2000 ,不能使用 stuff
亦不用函数

求大神
sql?server?字符串拼接

------解决方案--------------------
游标吧...
------解决方案--------------------
----------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2013-04-26 16:40:36
-- Version:
--      Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64) 
-- Jun 17 2011 00:54:03 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([mobile] int,[content] varchar(4))
insert [huang]
select 123,'qwer' union all
select 234,'qwer' union all
select 345,'qwer' union all
select 456,'asdf' union all
select 567,'asdf' union all
select 678,'sdfg' union all
select 789,'wert'
--------------开始查询--------------------------
--手动创建函数
ALTER  FUNCTION [dbo].[F_Str] ( @content VARCHAR(64) )
RETURNS NVARCHAR(1000)
AS 
    BEGIN
        DECLARE @S NVARCHAR(100)
        SELECT  @S = ISNULL(@S + ',', '') + CONVERT(VARCHAR(64), mobile)
        FROM    [huang]
        WHERE   [content] = @content
        RETURN @S
    END   
    --查询  
    SELECT DISTINCT  content,mobile=dbo.f_str(content) FROM [huang] 

----------------结果----------------------------
/* 
content mobile
------- ----------------------------------------------------------------------------------------------------------------
asdf    456,567
qwer    123,234,345
sdfg    678
wert    789
*/