1

I have two scenarios of inserting json string. I check the json string is already exists or not using the below code and then I insert into the table

**Scenario - 1**


 declare @jsonStr nvarchar(max) = {"Manufacurer": "test", "Model": "A", "Color":"New Color","Thickness":"1 mm"}
        declare @SqlStr nvarchar(max), @counts int

        Select @dynamicFilter = Coalesce(@dynamicFilter,'') +' and Json_Value(ItemOfProduct,''$."'+ [key] +'"'') = ''' +[value]+'''' from openjson(jsonStr)

        set @SqlStr = 'select @cnt = count(*) from tblTest where '+@dynamicFilter
        Exec sp_executesql @SqlStr, N'@cnt int output', @cnt = @counts output

        if(@counts < 1)
        Begin
            //insert the data into the table
        End




**Scenario - 2** 


set @jsonStr = {"Manufacurer": "test", "Model": "A", "Color":"New Color"}
    //Do the same above process of inserting

In the 2nd Scenario, my data is not getting inserted into table as the count is 1. But I want both the string in scenario 1 and 2 to be treated as different and both the data to be inserted into database.

1
  • What's the structure of tblTest? Are there any constraints on the table? What code are you actually using to try to insert the records into the table? Your code seems to be missing a pieces needed to help you debug it. Commented Nov 27, 2017 at 15:54

1 Answer 1

3

I think the best solution here is actually to use JSON_QUERY instead of JSON_VALUE, since your keys may be dynamic. Once you switch to JSON_QUERY, you no longer need to execute dynamic SQL.

CREATE TABLE #tblTest
(
    id INT IDENTITY(1, 1)
    ,ItemOfProduct NVARCHAR(MAX)
);


/*Scenario 1*/
DECLARE @jsonStr NVARCHAR(MAX) = N'{"Manufacturer": "test", "Model": "A", "Color":"New Color","Thickness":"1 mm"}';
DECLARE @counts INT;

SELECT @counts = COUNT(*)
FROM #tblTest
WHERE JSON_QUERY(ItemOfProduct, '$') = JSON_QUERY(@jsonStr, '$');

IF(@counts < 1)
BEGIN
    INSERT INTO #tblTest(ItemOfProduct)
    VALUES(@jsonStr);
END;


/*Scenario 2*/
SET @jsonStr =
    N'{"Manufacturer": "test", "Model": "A", "Color":"New Color"}';

SELECT @counts = COUNT(*)
FROM #tblTest
WHERE JSON_QUERY(ItemOfProduct, '$') = JSON_QUERY(@jsonStr, '$');

IF(@counts < 1)
BEGIN
    INSERT INTO #tblTest(ItemOfProduct)
    VALUES(@jsonStr);
END;

SELECT *
FROM #tblTest;
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.