SP_ABC存储过程中经过处理产生临时表#temp_01
temp_01里面主要的2个字段,user_id, role_name
#temp_01数据例子如下:
user_id role_name
1 工程师
1 巡检员
1 指挥中心
2 区域管理员
。。。
希望能把#temp_01的role_name的行的值变成列,并用“,”隔开
user_id role_names
1 工程师,巡检员,指挥中心
2 区域管理员
。。。
------解决方案--------------------
--合并字段到同一栏位
create?table?test_a
(
code?VARCHAR(10),
remark?VARCHAR(10)
)
insert?into?test_a
select?'A','1'?UNION
select?'A','2'?UNION
select?'A','3'?UNION
select?'B','11'?UNION
select?'B','22'?UNION
select?'C','33'?
--code????remark
--A????1,2,3
--B????11,22
--C????33
--执行查询
?select?code?,stuff((SELECT?','?+?b.remark?FROM?test_a?AS?b?WHERE?b.code?=?a.code?FOR?XML?PATH(''))?,1,1,'')?FROM?test_a?AS?a?GROUP?BY?code
?--执行结果
?----------?-----------------
A??????????1,2,3
B??????????11,22
C??????????33
?
(3?行受影响)
------解决方案--------------------
----------------------------------------------------------------
-- Author :DBA_HuangZJ(發糞塗牆)
-- Date :2014-07-07 11:11:56
-- Version:
-- Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
go
create table [TB]([user_id] int,[role_name] varchar(10))
insert [TB]
select 1,'工程师' union all
select 1,'巡检员' union all
select 1,'指挥中心' union all
select 2,'区域管理员'
--------------开始查询--------------------------
select a.[user_id],
stuff((select ','+[role_name] from tb b
where b.[user_id]=a.[user_id]
for xml path('')),1,1,'') [role_name]
from tb a
group by a.[user_id]
----------------结果----------------------------
/*
user_id role_name
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 工程师,巡检员,指挥中心
2 区域管理员
*/
------解决方案--------------------
2000写法
go
if object_id('F_Str') is not null
drop function F_Str
go
create function F_Str(@Col1 int)
returns nvarchar(100)
as
begin
declare @S nvarchar(100)
select @S=isnull(@S+',','')+[role_name] from tb where [user_id]=@Col1
return @S
end
go
Select distinct [user_id],Col2=dbo.F_Str([user_id]) [role_name] from tb
go