如标题 怎样使查询的结果就是一个字符串 SqlServer2005
Create TABLE User
(
int id identity(1,1) primary key,
nvarchar(50) UserName
)
姓名 数据库中存储的是 1,张三,2,李四,3,王五
怎样使查询结果成为 张三,李四,王五 在一行?
------解决方案--------------------
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-02-25 17:46:16
-- 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]([id] int,[UserName] varchar(4))
insert [huang]
select 1,'张三' union all
select 2,'李四' union all
select 3,'王五'
--------------开始查询--------------------------
SELECT DISTINCT
STUFF(( SELECT ',' + UserName
FROM [huang] b
FOR
XML PATH('')
), 1, 1, '') 'UserName'
FROM [huang] a
----------------结果----------------------------
/*
UserName
----------------------------------------------------------------------------------------------------------------
张三,李四,王五
*/