在 T-SQL 中拆分一列

Split a column in T-SQL

我刚开始使用 T-SQL, 如何用以下信息分隔 NVARCHAR 列

[3293,"Maria","CA","Auto"]
[67093,"Joana","WA","Manual"]

我想要这样的 4 列

col1   col2    col3  col4
3293   Maria   CA    Auto
67093  Joana   WA    Manual

谢谢

您可以使用 openjson 并汇总:

select
 max(case when [key] = 0 then value end) col1,
 max(case when [key] = 1 then value end) col2,
 max(case when [key] = 2 then value end) col3,
 max(case when [key] = 3 then value end) col4
from OpenJson('[3293,"Maria","CA","Auto"]')

无需聚合。

例子

Select Col1 = JSON_VALUE([SomeCol],'$[0]')
      ,Col2 = JSON_VALUE([SomeCol],'$[1]')
      ,Col3 = JSON_VALUE([SomeCol],'$[2]')
      ,Col4 = JSON_VALUE([SomeCol],'$[3]')
 From YourTable A
 

结果

Col1    Col2    Col3    Col4
3293    Maria   CA      Auto
67093   Joana   WA      Manual

 

使用 'OpenJson' 并循环传递列值。

--Step1: Create a Temporary table and add Row_Number

select ROW_NUMBER() over( order by COL) as r,* 
INTO #Temp_table
from YourTable;

--Step2: Declare and set Variables

DECLARE @count INT;
DECLARE @row INT;
DECLARE @JSON NVARCHAR(250);
set @count= (select COUNT(1) FROM #Temp_table);
SET @row = 1;

--Step3: Create Final table (Here, using temp final table)
CREATE TABLE #TEMP_FINAL 
(COL1 INT,COL2 VARCHAR(100),COL3 VARCHAR(100),COL4 VARCHAR(100));

--Step4: Iterate over loop

WHILE (@row <= @count) BEGIN
    
    SELECT @JSON=COL FROM #Temp_table WHERE @row=r;
    
    INSERT INTO #TEMP_FINAL
    select
    max(case when [key] = 0 then value end) col1,
    max(case when [key] = 1 then value end) col2,
    max(case when [key] = 2 then value end) col3,
    max(case when [key] = 3 then value end) col4
    from OpenJson(@JSON);
    
    SET @row += 1;
END 

--Step5: Select the values

SELECT * FROM #TEMP_FINAL

要了解,您可以查看以下链接

Row_Number: https://www.sqlservertutorial.net/sql-server-window-functions/sql-server-row_number-function/ While 循环:https://www.sqlshack.com/sql-while-loop-with-simple-examples/

还有一个建议使用技巧将 json 数组填充到另一个数组中。这允许 type-safe(!) 和 pivot/aggregate-free WITH-子句:

声明一个虚拟对象 table 以提供展示(请在下一个问题中自行完成)。

DECLARE @dummyTable TABLE(ID INT IDENTITY, YourJson NVARCHAR(MAX));
INSERT INTO @dummyTable(YourJson) VALUES
 ('[3293,"Maria","CA","Auto"]')
,('[67093,"Joana","WA","Manual"]');

--查询

SELECT t.ID
      ,JsonValues.*
FROM @dummyTable t
CROSS APPLY OPENJSON(CONCAT('[',t.YourJson,']'))
            WITH
            (
             TheNumber int           '$[0]'
            ,Firstname nvarchar(100) '$[1]'
            ,[State]   nvarchar(100) '$[2]'
            ,[Type]    nvarchar(100) '$[3]'
            ) JsonValues;

简而言之:

  • 我们使用 CONCAT() 在您的数组周围添加一个 [ 和一个 ]
  • 现在我们可以使用 WITH 指定结果列的名称、类型和 json 获取它的路径。

结果:

+----+-----------+-----------+-------+--------+
| ID | TheNumber | Firstname | State | Type   |
+----+-----------+-----------+-------+--------+
| 1  | 3293      | Maria     | CA    | Auto   |
+----+-----------+-----------+-------+--------+
| 2  | 67093     | Joana     | WA    | Manual |
+----+-----------+-----------+-------+--------+