Skip to content
Advertisement

Detect duplicate JSON nodes in JSON parameter before insert in SQL Server table

I want to detect duplicate nodes from JSON before insert them in SQL Server table.

I have this stored procedure that takes a JSON parameter like this:

CREATE PROCEDURE Core.myModelEditAction
    @OrganPersonID INT,
    @SalaryItems  NVARCHAR(2000),
    @AcceptLanguage NVARCHAR(50) = "fa"
AS
    DECLARE @Message NVARCHAR(MAX) = N''
BEGIN
    BEGIN TRY
        BEGIN TRANSACTION
            INSERT INTO Core.PersonSalary (OrganPersonID, SalaryItemID, Amount)
                SELECT @OrganPersonID, SalaryItemID, Amount
                FROM OPENJSON (@SalaryItems)
                     WITH (OrganPersonID int,
                           SalaryItemID int,
                           Amount int) 

I want to return exception if @SalaryItems has duplicate key

How can I detect

SELECT @OrganPersonID, SalaryItemID, Amount
FROM OPENJSON (@SalaryItems)

duplicate in this table in my code?

Advertisement

Answer

Use OPENJSON() without a with clause so that it returns the raw key, value and type columns, e.g.:

declare @SalaryItems nvarchar(2000) = N'{
  "OrganPersonID": 1,
  "SalaryItemID": 1,
  "Amount": 1,
  "SalaryItemID": 1,
  "SalaryItemID": 1
}';

-- Detect duplicated keys...
select [key], count(1) as count
from openjson(@SalaryItems)
group by [key]
having count(1) > 1;
key           count
------------- -----
SalaryItemID      3
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement