Parameterized OPENJSON in SQL Server query using Entity Framework Core

Viewed 2129
context.Set<BlogKeyValuePair>()
   .FromSql("SELECT [key], value FROM OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId=1), '$.@path')", 
        new SqlParameter("@path", "path.to.data"));

On first sighting this should work correctly and @path should be replace by path.to.data but it doesn't, an SqlException is thrown with the following error:

System.Data.SqlClient.SqlException: Incorrect syntax near '@path'.

Seems like SQL server does not replace the parameter because it is a parameter inside the OPENJSON function.

Looking for secure workarounds.

2 Answers

SQL does not recognize the variable because you put it inside a string:

-- Wrong:
OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId = 1), '$.@path')

-- Correct:
OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId = 1), '$.' + @path)

Code:

context
    .Set<BlogKeyValuePair>()
    .FromSql(@"
        SELECT [key], value
        FROM OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId = 1), '$.' + @path)",
        new SqlParameter("@path", "path.to.data"));

This works for me in SSMS, so @marsze's answer should work.

declare @path nvarchar(2000) = 'ArrayValue';

DECLARE @json NVARCHAR(4000) = N'{  
   "StringValue":"John",  
   "IntValue":45,  
   "TrueValue":true,  
   "FalseValue":false,  
   "NullValue":null,  
   "ArrayValue":["a","r","r","a","y"],  
   "ObjectValue":{"obj":"ect"}  
}'

SELECT *
FROM OPENJSON(@json, '$.' + @path)
Related