如何将这个字符串拆分为UDF

时间:2019-05-31 14:37:48

标签: sql-server user-defined-functions

我有此列(来自BigCommerce数据库的导出),将自定义字段保留在单个列中。这是数据的一个示例:

[{"Name":"Unit Number","Value":"3698"},{"Name":"Region","Value":"Eastern Great Lakes (WNY, W PA)"}]

我需要一种方法来弄清楚如何从中提取字段/值对。在此示例中,我想获得以下输出:

Unit Number:3698
Region:Eastern Great Lakes (WNY, W PA)

因此,我希望有一个UDF可以作为选择查询的一部分运行,该查询可以为我提供字段名和以字符串形式输出的值(如上例所示)。源表中的每一列数据都具有这种格式。通常,列数据具有两个字段/值对,但有时没有,有时是两个,有时是三个。换句话说,该列包含任意数量的可变字段/值对。

有人对如何构建UDF以帮助从字符串中获取这些数据元素有任何建议吗?

我一直在捣乱事物,但是我被困住了。我首先尝试删除无关的[,](无意义)和{,}(它们描绘了字段和值)。我在修改字符串拆分功能,但是除了拆分单个字符外,我无法弄清楚如何根据成对的{,}来缩小拆分范围。

Unit Number:3698 | Region:Eastern Great Lakes (WNY, W PA)

1 个答案:

答案 0 :(得分:0)

DECLARE @json NVARCHAR(MAX)
SET @json =  N'[{"Name":"Unit Number","Value":"3698"},{"Name":"Region","Value":"Eastern Great Lakes (WNY, W PA)"}]' 

--read from json
SELECT [Name], [Value]  
FROM OPENJSON(@json)
  WITH ([Name] NVARCHAR(100) '$.Name',  
        [Value] NVARCHAR(50) '$.Value')  

--if it has only these two fixed cols like Unit Number, Region starts here
SELECT [Region],[Unit Number] from 
             (
                SELECT [Name], [Value]  
                    FROM OPENJSON(@json)
                      WITH ([Name] NVARCHAR(100) '$.Name',  
                            [Value] NVARCHAR(50) '$.Value') 
            ) x
            pivot 
            (
                MAX([Value])
                for [Name] in ([Region],[Unit Number])
            ) p 
--if it has only these two fixed cols like Unit Number, Region ends here

--********if it has dynamic columns starts here********
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME([Name])  
            FROM OPENJSON(@json)
              WITH ([Name] NVARCHAR(100) '$.Name',  
                    [Value] NVARCHAR(50) '$.Value') 

            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @query = 'SELECT ' + @cols + ' from 
             (
                SELECT [Name], [Value]  
                    FROM OPENJSON(@json)
                      WITH ([Name] NVARCHAR(100) ''$.Name'',  
                            [Value] NVARCHAR(50) ''$.Value'') 
            ) x
            pivot 
            (
                MAX([Value])
                for [Name] in (' + @cols + ')
            ) p ' 

print @query
EXEC sp_executesql @query, N'@json NVARCHAR(MAX)', @json
--********if it has dynamic columns ends here********

注意:仅适用于MSSQL 2016/17或更高版本(已使用v17.1)