我在資料庫中有一個物件,我相信可以使用 OPENJSON 對其進行決議。如果有更好的解決方案,我絕對愿意接受。下面的值是虛構的。
桌子
DROP TABLE IF EXISTS #temp;
CREATE TABLE #temp (
ID INT,
Object VARCHAR(MAX)
);
INSERT INTO #temp
(
ID,
Object
)
VALUES
( 1, '{ "Country": "US", "CountryName": "United States of America", "Inflation": 5.0 }'),
( 2, '{ "Country": "MX", "CountryName": "Mexico", "Inflation": 6.0 }'),
( 3, '{ "Country": "CA", "CountryName": "Canada, "Inflation": 5.5 }');
嘗試的解決方案
SELECT *
FROM OPENJSON((SELECT Object FROM #temp))
WITH (
Country CHAR(2) '$.Country',
CountryName VARCHAR(MAX) '$.CountryName',
Inflation DECIMAL(2,1) '$.Inflation'
)
結果
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
期望的結果
| ID | 國家 | 國家的名字 | 通貨膨脹 |
|---|---|---|---|
| 1 | 我們 | 美國 | 5.0 |
| 2 | MX | 墨西哥 | 6.0 |
| 1 | 加州 | 加拿大 | 5.5 |
任何幫助將不勝感激!
uj5u.com熱心網友回復:
在加拿大之后添加“... 使用 CROSS APPLY
Select A.ID
,B.*
From #temp A
Cross Apply (
SELECT *
FROM OPENJSON(Object)
WITH (
Country CHAR(2) '$.Country',
CountryName VARCHAR(MAX) '$.CountryName',
Inflation DECIMAL(2,1) '$.Inflation'
)
) B
結果

編輯
或- 如果您的 JSON 如此簡單,那么以下內容會更高效。
Select A.ID
,Country = JSON_VALUE(Object,'$.Country')
,CountryName = JSON_VALUE(Object,'$.CountryName')
,Inflation = JSON_VALUE(Object,'$.Inflation')
From #Temp A
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/485002.html
