2017-10-20 151 views
1

我被困在更新/插入來自JSON數組行到SQL Server 2017TSQL更新

我有以下結構:

{ 
    "ID":52, 
    "Name":"Mark", 
    "Surname":"Blake", 
    "Age": 24 
    "Cars":[ 
     {"ID":110,"Volvo":"2001-10-01","Color":"red"}, 
     {"ID":110,"Volvo":"2001-10-01","Color":"red"}, 
     {"ID":110,"Volvo":"2001-10-01","Color":"red"}, 
     {"ID":-1,"Volvo":"2001-10-01","Color":"red"}, 
     {"ID":-1,"Volvo":"2001-10-01","Color":"red"}, 
    ] 
} 

我試圖做一個合併基礎上Cars數組,當ID爲-1時插入到表中,否則更新。

如何實現這一目標?

好的,我做到了,但我又遇到了另一個問題。 我想從更高的層次也得到ID(我的意思是52在這種情況下),它應該是這樣的:

110 52 2001-10-01 red 
110 52 2001-10-01 red 
110 52 2001-10-01 red 
-1 52 2001-10-01 red 
-1 52 2001-10-01 red 

回答

1

我定你JSON,這是一個有點不正確。

DECLARE @json nvarchar(max) = '{ 
    "ID":52, 
    "Name":"Mark", 
    "Surname":"Blake", 
    "Age": 24, 
    "Cars":[ 
     {"ID":110,"Volvo":"2001-10-01","Color":"red"}, 
     {"ID":110,"Volvo":"2001-10-01","Color":"red"}, 
     {"ID":110,"Volvo":"2001-10-01","Color":"red"}, 
     {"ID":-1,"Volvo":"2001-10-01","Color":"red"}, 
     {"ID":-1,"Volvo":"2001-10-01","Color":"red"} 
    ] 
}' 


SELECT JSON_VALUE(t.[value], N'$.ID'), 
     JSON_VALUE(t.[value], N'$.Volvo'), 
     JSON_VALUE(t.[value], N'$.Color') 
FROM OPENJSON(@json, N'$.Cars') as t 

輸出:

110 2001-10-01 red 
110 2001-10-01 red 
110 2001-10-01 red 
-1 2001-10-01 red 
-1 2001-10-01 red 

將在CTE或臨時表,然後合併主表。或者你可以先INSERT(WHERE ID = -1)和UPDATE(WHERE ID != -1

更新:

SELECT f.[value], 
     JSON_VALUE(c.[value], N'$.ID'), 
     JSON_VALUE(c.[value], N'$.Volvo'), 
     JSON_VALUE(c.[value], N'$.Color') 
FROM OPENJSON(@json) f 
CROSS APPLY OPENJSON(@json,N'$.Cars') c 
WHERE f.[key] IN ('ID') 

輸出:

52 110 2001-10-01 red 
52 110 2001-10-01 red 
52 110 2001-10-01 red 
52 -1 2001-10-01 red 
52 -1 2001-10-01 red 
+0

我也用同樣的只是幾分鐘前,但我我們遇到了另一個問題。 我想從更高級別(我的意思是52在這種情況下)的ID,它應該看起來像: 110 52 2001-10-01紅色 110 52 2001-10-01紅色 110 52 2001- 10-01紅色 -1 52 2001-10-01紅色 -1 52 2001-10-01紅色 – tylkonachwile

+0

你知道如何做到這一點嗎?我編輯了我的帖子。感謝幫助! – tylkonachwile

+0

如果你的JSON不會超過1個數據區,你可以簡單地添加'JSON_VALUE(@ json,N'$ .ID')' – gofr1