【问题标题】:How to make this stored procedure use a JSON check?如何让这个存储过程使用 JSON 检查?
【发布时间】: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


    【解决方案1】:

    我希望我理解你的正确。 请试试这个:

    ;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)
    ;
    

    任何问题也请告诉我。

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 2018-10-03
      • 2014-10-04
      • 1970-01-01
      • 2011-08-08
      • 1970-01-01
      • 2019-08-06
      • 2011-09-17
      • 1970-01-01
      相关资源
      最近更新 更多