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?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With