sql - 如何让这个存储过程使用 JSON 检查?
问题描述
我正在考虑使用存储过程来帮助解决我必须更新/插入大约 1000 条记录的情况。有人建议我使用MERGE
表值参数来实现这一点,但问题是其中一列是 JSON 字符串。
项目表
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
作为参数,然后自行提取出来?
解决方案
我希望我理解你的正确。请试试这个:
;WITH MergeTarget AS (
SELECT t.BrandId,t.LocationId,t.Field3,JSON_VALUE(t.Field3,'$.itemNumber') AS [ItemNumber],t.OtherParam
FROM Table1 AS t
)
MERGE MergeTarget AS target
USING (
SELECT s.BrandId,s.LocationId,s.ItemNumber,'{"itemNumber":"'+CONVERT(NVARCHAR(255),s.ItemNumber)+'"' AS [Field3],s.OtherParam
FROM @Source AS s
) AS source ON source.BrandId = target.BrandId
AND source.LocationId = target.LocationId
AND source.ItemNumber = target.ItemNumber
WHEN MATCHED AND target.OtherParam <> source.OtherParam THEN UPDATE SET target.OtherParam = source.OtherParam
WHEN NOT MATCHED THEN INSERT (BrandId, LocationId, Field3, OtherParam)
VALUES(source.BrandId,source.LocationId,source.Field3,source.OtherParam)
;
有任何问题也请告诉我。
推荐阅读
- r - 从第三次观察开始,在 R 中进行黄土曲线拟合
- scala - 没有参数评估 zeppelin 中定义的 Scala 方法
- python - 如何基于单个列上的多个 StringMethods 有效且惯用地过滤 PandasDF 行?
- linux-kernel - 在 5.4 中编译 gpio-mockup
- php - Yii2 gridView 从 hasMany 关系中排序最后一条记录
- ios - 在 iOS 上的 Cognito 中,处理所需的新密码永远不会达到 didCompleteNewPasswordStepWithError
- python-3.x - 如何在一周内使用 SQLALCHEMY (Flask) 从数据库中选择所有项目
- c# - 如何使用 webdriver 选择合适的 iframe?
- jquery - iPad / Safari 未传递 Window.Name 值
- haskell - “无法加载模块'Control.Monad.State'它是隐藏包'mtl-2.2.2'的成员”使用runhaskell时出错