【发布时间】:2019-01-23 17:01:22
【问题描述】:
我正在考虑使用存储过程来帮助解决我必须更新/插入大约 1000 条记录的情况。有人建议我使用带有表值参数的MERGE 来实现此目的,但问题是其中一列是 JSON 字符串。
ItemsTbl
id -PK
BrandId- int (FK)
LocationId- int (FK)
Field3 - nvarchar(Max) Json string containing a jsonKey called itemNumber
select *
from ItemsTbl
where BrandId = 1
and LocationId = 1
and JSON_VALUE('Field3',$.itemNumber) = 12345
现在存储过程(对我来说几乎是全新的)现在看起来像这样:
/* Create a table type. */
CREATE TYPE SourceTableType AS TABLE
( BrandId INT
, LocationId INT
, ItemNumber INT
, ...
);
GO
CREATE PROCEDURE dbo.usp_InsertTvp
@Source SourceTableType READONLY
AS
MERGE INTO Table1 AS Target
USING @Source As Source ON Target.BrandId = Source.BrandId
AND Target.LocationId = Source.LocationId
AND Target.ItemNumber = Source.ItemNumber
WHEN MATCHED THEN
UPDATE SET OtherParam = Source.OtherParam
WHEN NOT MATCHED BY TARGET THEN
INSERT (BrandId, LocationId, ItemNumber, OtherParam)
VALUES (BrandId, LocationId, ItemNumber, OtherParam) ;
问题在于,现在似乎并没有考虑到 ItemNumber 在 JSON 字符串中,而不是它自己的列。所以我认为这行不通
Target.ItemNumber = Source.ItemNumber
另外我猜SourceTableType 必须接受Field3 作为参数,然后自己提取出来?
【问题讨论】:
标签: sql json sql-server stored-procedures sql-server-2017