创建一个列转行的函数 udf_ConvertStrToTable
/* -- 如将以某个字符相隔的字符串字符串转换为表 -- 如字符串:Nothing,is,impossible,to,a,willing,heart -- SELECT * FROM udf_ConvertStrToTable(‘Nothing,is,impossible,to,a,willing,heart‘, ‘,‘) */ CREATE FUNCTION [dbo].[udf_ConvertStrToTable] ( @Str NVARCHAR(MAX), @SplitSymbol CHAR(1) = ‘,‘ ) RETURNS @aTable TABLE ( Iden INT, Item VARCHAR(500) ) AS BEGIN DECLARE @i INT SET @i = 0 WHILE RIGHT(@Str, 1) = @SplitSymbol SET @Str = LEFT(@Str, LEN(@Str) - 1) DECLARE @iIndex INT SET @iIndex = CHARINDEX(@SplitSymbol, @Str) WHILE @iIndex > 0 BEGIN SET @i = @i + 1 INSERT INTO @aTable ( Iden, Item ) VALUES (@i, LEFT(@Str, @iIndex - 1)) SELECT @Str = SUBSTRING(@Str, @iIndex + 1, 6000) SET @iIndex = CHARINDEX(@SplitSymbol, @Str) END IF LTRIM(RTRIM(@Str)) <> ‘‘ BEGIN INSERT INTO @aTable ( Iden, Item ) VALUES (@i + 1, @Str) END RETURN END
具体用法:
DECLARE @Sample VARCHAR(MAX) = ‘Nothing,is,impossible,to,a,willing,heart‘; -- 列转行 SELECT * FROM udf_ConvertStrToTable(@Sample, ‘,‘) -- 行转列 SELECT * INTO #Temp FROM udf_ConvertStrToTable(@Sample, ‘,‘) -- 将上面同样的查询结果写入临时表 #Temp SELECT STUFF((SELECT ‘,‘ + A.Item FROM #Temp A ORDER BY Iden FOR XML PATH(‘‘)), 1, 1, ‘‘) AS Result DROP TABLE #Temp -- 删除临时表
执行效果: