[英]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. 我正在尝试编写一个存储过程,该过程为part表创建了标题行。
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. 我想直接将ID插入标题行表中,并且想使用JSON对象中的UserName字段来查找要插入标题行表中的UserID。
I can't figure out how to assign the JSON values to variables. 我不知道如何将JSON值分配给变量。
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 消息207,第16级,州1,第41行
Invalid column name 'id'. 无效的列名“ id”。
Msg 207, Level 16, State 1, Line 43 消息207,第16层,状态1,第43行
Invalid column name 'UserName'. 无效的列名“ UserName”。
What am I doing wrong? 我究竟做错了什么?
you can do the variable assignment like this 您可以像这样进行变量分配
SELECT
@VehicleID = Id
, @UserName = UserName
FROM
OPENJSON (@json)
WITH
(
Id INT
, UserName NVARCHAR(50)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.