SQL Server中将字符串的列转行和行转列

创建一个列转行的函数 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  -- 删除临时表

 

执行效果:

SQL Server中将字符串的列转行和行转列

 

SQL Server中将字符串的列转行和行转列

上一篇:MongoDB 逻辑备份工具mongodump


下一篇:PHP7.2 装mongodb 遇到的坑,完美解决!