Q: How do I assign a JSON value to a variable in TSQL? I am trying to write a stored procedure that creates a header row for a parts table.
I want insert the ID directly into the header row table, and I want to use the UserName field from the JSON object to find the UserID to insert into the header row table.
I can't figure out how to assign the JSON values to variables.
Here is my script:
DECLARE @Json NVARCHAR(MAX) = '{

            "Id":1,
            "SerialNumber":425,
            "Model":"T8X",
            "UserName":"BRASKYB",
            "EquipmentParts" : {
                    "WWECode": "21-21-0100"
            ,       "WWEDescription": "GERMAN SUPLEX"
            ,       "BFE": "101HD"
            ,       "Manufacturer": "THE PAWN SHOP"
            ,       "ManufacturerCode": "U69420"
            ,       "PartNumber": "867530-9"
            ,       "SerialNumber": "420"
            ,       "Amendment": ""
            ,       "Remarks": ""
                
            }
        }
        '
DECLARE @VehicleID          INT;
DECLARE @LoadedOn           DATE = GETDATE();       
DECLARE @LoadedBy           INT ;
DECLARE @UserName           VARCHAR(50);



SELECT
    Id
,   UserName
FROM   
    OPENJSON (@json)
WITH
(
    Id INT
,   UserName NVARCHAR(50)
) 


SELECT  @VehicleID = json.ID
SELECT  @UserName = json.UserName


SELECT UserID = @Loadedby FROM master.[User] a WHERE a.UserName = @UserName

INSERT INTO 
    SERVER.SCHEMA.HeaderTable(
        VehicleId
    ,   LoadedOn
    ,   LoadedBy
    )
VALUES
    (
        @VehicleID
    ,   @LoadedOn
    ,   @LoadedBy
    )

I get the following error when trying to run this script:

Msg 207, Level 16, State 1, Line 41
Invalid column name 'id'.
Msg 207, Level 16, State 1, Line 43
Invalid column name 'UserName'.

What am I doing wrong?

A: you can do the variable assignment like this
SELECT
   @VehicleID = Id
,  @UserName = UserName
FROM   
    OPENJSON (@json)
WITH
(
    Id INT
,   UserName NVARCHAR(50)
) 

