我正在尝试编写一个存储过程,为部件表创建标题行。
我想直接将ID插入标题行表,我想使用JSON对象中的UserName字段来查找要插入标题行表的UserID。
我无法弄清楚如何将JSON值分配给变量。
这是我的剧本:
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
)
尝试运行此脚本时出现以下错误:
Msg 207,Level 16,State 1,Line 41
列名称无效' id'。
Msg 207,Level 16,State 1,Line 43
列名称无效'用户名'。
我做错了什么?
答案 0 :(得分:0)
你可以像这样进行变量赋值
SELECT
@VehicleID = Id
, @UserName = UserName
FROM
OPENJSON (@json)
WITH
(
Id INT
, UserName NVARCHAR(50)
)