我是使用 T-SQL 的新手,如何用以下資訊分隔 NVARCHAR 列
[3293,"Maria","CA","Auto"]
[67093,"Joana","WA","Manual"]
我想得到這樣的 4 列
col1 col2 col3 col4
3293 Maria CA Auto
67093 Joana WA Manual
謝謝
uj5u.com熱心網友回復:
無需聚合。
例子
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
uj5u.com熱心網友回復:
您可以使用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"]')
uj5u.com熱心網友回復:
另一個建議使用技巧將 json 陣列填充到另一個陣列中。這允許使用型別安全(!)和無樞軸/無聚合的WITH子句:
宣告一個虛擬表來提供展示(請在下一個問題中自己做)。
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()添加 a[和 a 。] - 現在我們可以使用
WITH指定帶有名稱、型別和 json 路徑的結果列來獲取它。
結果:
---- ----------- ----------- ------- --------
| ID | TheNumber | Firstname | State | Type |
---- ----------- ----------- ------- --------
| 1 | 3293 | Maria | CA | Auto |
---- ----------- ----------- ------- --------
| 2 | 67093 | Joana | WA | Manual |
---- ----------- ----------- ------- --------
uj5u.com熱心網友回復:
使用“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 -例子/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/425870.html
上一篇:SQLServer我們如何撰寫一個sql函式來回傳getdate()在FromDate和Todate之間的記錄
下一篇:使用特定邏輯合并SQL中的行
