在开发sql server语序中,可能需要这样一个要求,把表中某一列的所有值转换为使用逗号分隔的字符串去呈现出来。
举个例子:
if object_id('tempdb..#temptable') is not null
begin
drop table #temptable
end
create table #temptable ([id] int not null,[category] nvarchar(40) null)
insert into #temptable ([id],[category]) values (1,'table'),
(2,'view'),
(3,'store procedure'),
(4,'table-valued function'),
(5,'scalar-valued function'),
(6,'user-defined table type')
select [id],[category] from #temptable
go
要求结果,[id]或[category]任意一列,呈现如下:
日后,我们不清楚是哪一张表,哪一个字段。
因此,可以写成一个动态的sql 存储过程来处理:
set ansi_nulls on
go
set quoted_identifier on
go
-- =============================================
-- author: insus.net
-- create date: 2019-05-11
-- update date: 2019-05-11
-- description: 列值转换为逗号分隔字符串
-- =============================================
create procedure [dbo].[usp_tablecolumnvaluetocommadelimitedstring] (
@tablename sysname,
@columnname sysname,
@returnvalue nvarchar(max) output
)
as
begin
declare @sql nvarchar(max) = n'
declare @temporary_table as table([multirow_comma-delimited_string] nvarchar(max))
insert into @temporary_table ([multirow_comma-delimited_string])
select top(1) stuff(
replace(
rtrim(
(select ''|'' + cast('+ @columnname +' as nvarchar(max)) from '+ @tablename +' for xml path('''') )
),
''|'','', ''),
1,1,'''') from '+ @tablename +'
select @returnvalue = [multirow_comma-delimited_string] from @temporary_table'
execute sp_executesql @sql,
n'@returnvalue nvarchar(max) output',
@returnvalue output
end
只要为上面存储过程传入表名,字段名等参数即可得到我们想要的结果: