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

如何将查询的多笔记录的某个字段组合成一个字符串?
比如: Select 工号,部门,性别 From Employee Where 部门 = '工程部'

假如结果有8笔记录,如何将这8笔记录的工号组合成一个字符串.用SQL函数返回.

------解决方案--------------------
select stuff((select ','+工号 from employee where 部门='工程部'),1,1,'')
------解决方案--------------------

if object_id('test') is not null drop table test
go
create table test(ccode varchar(3),bm nvarchar(10))
go
insert into test
select '001',N'工程部'
union all
select '002',N'工程部'
union all
select '003',N'工程部'

--创建函数
create function getstr(@bm nvarchar(100)) returns varchar(8000)
as
begin
declare @temp varchar(8000)
set @temp=''
select @temp=@temp+ccode from test where bm=@bm
return @temp

end

--调用函数
select dbo.getstr(N'工程部')

------解决方案--------------------

----------------------------
-- Author  :磊仔
-- Date    :2013-01-27 11:24:40
-- Version:  
--      Microsoft SQL Server 2008 (SP2) - 10.0.4000.0 (Intel X86)   
-- Sep 16 2010 20:09:22   
-- Copyright (c) 1988-2008 Microsoft Corporation  
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7600: )  
--
----------------------------
--> 测试数据:employee
use tempdb
GO
create table employee([工号] varchar(3),[部门] varchar(6),[性别] varchar(2))
insert employee
select 'G01','工程部','男' union all
select 'G02','工程部','男' union all
select 'G03','工程部','男' union all
select 'G04','工程部','女' union all
select 'G05','工程部','女' union all
select 'G06','工程部','女' union all
select 'G07','财务部','女'