patternsqlMinor
Passing variable as parameter to json_query function
Viewed 0 times
passingfunctionjson_queryvariableparameter
Problem
I am getting error:
The argument 2 of the "JSON_VALUE or JSON_QUERY" must be a string literal
...while trying to pass variable as parameter to
Sample data:
The argument 2 of the "JSON_VALUE or JSON_QUERY" must be a string literal
...while trying to pass variable as parameter to
JSON_QUERY function. Please help me to resolve it.DECLARE @cnt INT = 1;
DECLARE @cnt_total INT = 1;
DECLARE @json NVARCHAR(MAX);
DECLARE @json1 NVARCHAR(MAX);
declare @str VARCHAR(200);
WHILE @cnt <= 10
BEGIN
set @str = '$.Seasons[0].Products['+convert(varchar,@cnt)+'].ProductChannels';
set @str = char(39) +@str+ char(39);
PRINT @STR
select @json = json_query(jfile,@STR) from Import.tstjson;
--MORE CODE
SET @cnt = @cnt + 1;
ENDSample data:
{
"Seasons": [
{
"Season": "12321231",
"Products": [
{
"ProductId": "211",
"ProductChannels": [
{
"ChannelId": 1,
"WeekQuantities": []
}
],
"ccc": 3,
"Tttt": 4
}
]
}
]
}
Solution
It is possible in SQL Server 2017.
From JSON_QUERY (Transact-SQL)
In SQL Server 2017 and in Azure SQL Database, you can provide a
variable as the value of path.
In SQL Server 2016 you have to build the query dynamically.
From JSON_QUERY (Transact-SQL)
In SQL Server 2017 and in Azure SQL Database, you can provide a
variable as the value of path.
In SQL Server 2016 you have to build the query dynamically.
Context
StackExchange Database Administrators Q#199593, answer score: 9
Revisions (0)
No revisions yet.