SQL 服务器解析 JSON 更新另一个 table

SQL Server parse JSON to update another table

我有一个 table,其中一列中有 JSON 数据,我正在尝试解析 JSON 数据并插入临时 table

DECLARE @TEMPTABLE
( 
     ID INT, 
     Status NVARCHAR(50), 
     Cost DECIMAL(20, 0)
)


INSERT INTO @TEMPTABLE
    SELECT 
        ID, 
        JSON_VALUE(mydata, '$.Status') AS Status,
        JSON_VALUE(mydata, '$.Cost') AS Cost 
    FROM Expense

我收到这个错误:

Error Converting data type nvarchar to numeric

如果我注释掉 Cost 列,同样可以正常工作。

示例 JSON 数据成本 table

 | ID | mydata 
 +----+-------------------------------------
 | 1  | {"Status":"Shipped","Cost":".50"}

您可能需要将字符串转换为十进制值,请尝试以下操作:

DECLARE @TEMPTABLE
( ID INT , Status nvarchar(50), Cost DECIMAL(20,0))


INSERT INTO @TEMPTABLE
(
    ID,
    Status,
    Cost
)
SELECT 
    ID, 
    JSON_VALUE(mydata,'$.Status') AS [Status],
    TRY_CAST(REPLACE(JSON_VALUE(mydata,'$.Cost'), '$', '') AS DECIMAL(20,0)) AS [Cost]
FROM Expense

您可以将该值转换为 MONEY。它比 decimal()

更宽容一点

例子

Declare @Expense Table ([ID] int,mydata varchar(50))
Insert Into @Expense Values 
 (1,'{"Status":"Shipped","Cost":".50"}')
 
SELECT ID
      ,JSON_VALUE(mydata,'$.Status') as Status
      ,try_convert(money,JSON_VALUE(mydata,'$.Cost'))  as Cost 
 FROM @Expense

Returns

ID  Status  Cost
1   Shipped 10.50