SQL Server parse JSON to update another table

384 views Asked by At

I have a table with JSON data in one of the columns and i'm trying to parse the JSON data and insert into a temp 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

I get this error:

Error Converting data type nvarchar to numeric

The same works fine if I comment out the Cost column.

Sample JSON data in Cost table

 | ID | mydata 
 +----+-------------------------------------
 | 1  | {"Status":"Shipped","Cost":"$10.50"}
2

There are 2 answers

2
John Cappelletti On BEST ANSWER

You can convert the value to MONEY. It is a little more forgiving than decimal()

Example

Declare @Expense Table ([ID] int,mydata varchar(50))
Insert Into @Expense Values 
 (1,'{"Status":"Shipped","Cost":"$10.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
2
Hector Diaz Contreras On

You probably need to cast the string into a decimal value, give the following a try:

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