在開發SQL Server語序中,可能須要這樣一個要求,把表中某一列的全部值轉換爲使用逗號分隔的字符串去呈現出來。sql
舉個例子:ide
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]任意一列,呈現以下:函數
往後,咱們不清楚是哪一張表,哪個字段。spa
所以,能夠寫成一個動態的SQL 存儲過程來處理:3d
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
只要爲上面存儲過程傳入表名,字段名等參數便可獲得咱們想要的結果:code
如下內容於2019-05-22 08:48:44.633更新:blog
存儲過程,另外一個版本:ip
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[usp_TableColumnValueToCommaDelimitedString] ( @tableName SYSNAME, @columnName SYSNAME, @Comma_Delimited_Column_Names NVARCHAR(MAX) OUTPUT ) AS BEGIN DECLARE @query NVARCHAR(MAX) = N'SET @Comma_Delimited_Column_Names = STUFF((SELECT DISTINCT '','' + QUOTENAME('+ @columnName +') FROM '+ @tableName +' FOR XML PATH(''''), TYPE ).value(''.'', ''NVARCHAR(MAX)'') ,1,1,'''')' EXECUTE sp_executeSql @query, N'@Comma_Delimited_Column_Names AS NVARCHAR(MAX) OUTPUT',@Comma_Delimited_Column_Names OUTPUT END
獲得的結果,就是使用QUOTENAME函數,把每個列名使用"["和"]"括起來:開發