是否可以直接使用JSON更新表,而无需插入临时表?
下面的代码将数据插入临时表并更新原始表。
DECLARE @TempTelecommunicationsNumber AS TABLE (RoleID INT,Number VARCHAR(100),Ext VARCHAR(100))
INSERT INTO @TempTelecommunicationsNumber (RoleID,Number,Ext)
SELECT @RoleID, Number,Ext
FROM OPENJSON(@TelecommunicationsNumber)
WITH (RoleID INT, Number NVARCHAR(256), Ext NVARCHAR(256))
MERGE Party.TelecommunicationsNumber original
USING @TempTelecommunicationsNumber modified
ON (original.RoleID = modified.RoleID)
WHEN MATCHED
THEN UPDATE SET
original.Number = modified.Number,
original.Ext = modified.Ext
WHEN NOT MATCHED BY TARGET
THEN INSERT (RoleID,Number,Ext)
VALUES (@RoleID,modified.Number,modified.Ext);
有没有一种方法可以直接更新如下。
MERGE Party.TelecommunicationsNumber original
USING OPENJSON(@Json) modified
ON (original.RoleID = modified.RoleID)
WHEN MATCHED
THEN UPDATE SET
original.Number = modified.Number,
original.Ext = modified.Ext
WHEN NOT MATCHED BY TARGET
THEN INSERT (RoleID,Number,Ext)
VALUES (@RoleID,modified.Number,modified.Ext);
答案 0 :(得分:2)
是的,例如,可以使用公用表表达式:
WITH cte AS (
SELECT @RoleID AS RoleID, Number,Ext
FROM OPENJSON(@TelecommunicationsNumber)
WITH (RoleID INT, Number NVARCHAR(256), Ext NVARCHAR(256))
)
MERGE Party.TelecommunicationsNumber original
USING cte modified
ON (original.RoleID = modified.RoleID)
WHEN MATCHED
THEN UPDATE SET
original.Number = modified.Number,
original.Ext = modified.Ext
WHEN NOT MATCHED BY TARGET
THEN INSERT (RoleID,Number,Ext)
VALUES (@RoleID,modified.Number,modified.Ext);
或:
MERGE Party.TelecommunicationsNumber original
USING (SELECT @RoleID AS RoleID, Number,Ext
FROM OPENJSON(@TelecommunicationsNumber)
WITH (RoleID INT, Number NVARCHAR(256), Ext NVARCHAR(256))) modified
ON (original.RoleID = modified.RoleID)
WHEN MATCHED
THEN UPDATE SET
original.Number = modified.Number,
original.Ext = modified.Ext
WHEN NOT MATCHED BY TARGET
THEN INSERT (RoleID,Number,Ext)
VALUES (@RoleID,modified.Number,modified.Ext);