C# Dapper using JSON_VALUE for SQL Server 2016

空扰寡人 提交于 2019-12-19 03:24:10

问题


I want to query data from my table using JSON_VALUE:

var str = "123";
var value = "Name"
using(var conn = GetMyConnection())
{
   var result = conn.QueryFirstOrDefault<string>(
      @"SELECT [Id] FROM [dbo].[MyTable]
         WHERE JSON_VALUE([JsonColumn], @MyQuery) = @Str",
      new
      {
         MyQuery = $"$.{value}",
         Str = str
      }
   );
}

I try this in SQL Server, it is working:

SELECT [Id] FROM [dbo].[MyTable]
WHERE JSON_VALUE([JsonColumn], '$.Name') = '123'

How should I adjust my code?


回答1:


I try this in SQL Server, it working

First of all you miss one important thing variable vs literal.

It won't work on SQL Server 2016 when used in SSMS:

CREATE TABLE MyTAble(ID INT IDENTITY(1,1), JsonColumn NVARCHAR(MAX));

INSERT INTO MyTable( JsonColumn)
VALUES('{"Name":123}');


-- it will work
SELECT [Id] FROM [dbo].[MyTable]
WHERE JSON_VALUE([JsonColumn], '$.Name') = '123';

-- let''s try your example
DECLARE @Path NVARCHAR(MAX) = '$.Name';
SELECT [Id] FROM [dbo].[MyTable]
WHERE JSON_VALUE([JsonColumn], @Path) = '123';

DBFiddle Demo

You will get:

The argument 2 of the "JSON_VALUE or JSON_QUERY" must be a string literal.


Second from SQL Server 2017+ you could pass path as variable. From JSON_VALUE:

path

A JSON path that specifies the property to extract. For more info, see JSON Path Expressions (SQL Server).

In SQL Server 2017 and in Azure SQL Database, you can provide a variable as the value of path.

DbFiddle Demo 2017


And finally to get it work on SQL Server 2016 you may build your query string using concatenation (instead of parameter binding).

Warning! This could lead to serious security problem and SQL Injection attacks.



来源:https://stackoverflow.com/questions/46860751/c-sharp-dapper-using-json-value-for-sql-server-2016

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!