For the following query, I receive the error when running it:
The argument 2 of the "JSON_VALUE or JSON_QUERY" must be a string literal.
SELECT JSON_QUERY(sr.Options, CONCAT('$[', sr.OptionId,']')
FROM Survey as sr
The column 'Options' contains JSON similar to this: [{"Id":1, "Text": "Yes"},{"Id":2, "Text": "No"}] and 'OptionId' relates to the index of one of these options which I want to return, but is nullable and in that case, I don't care what it returns. 'Options' will also sometimes be an empty array '[]' but in that case 'OptionId' is always NULL.
This is being run against SQL Server 13.0.4001
I attempted various things on argument 2 of JSON_QUERY such as using a case statement to only use sr.OptionId when it is not null, trying to convert the type, and a where statement on the entire query to filter out null.
1条答案
按热度按时间prdp8dxp1#
You may try a different statement using
OPENJSON()
with default schema and an additionalAPPLY
operator. The result from theOPENJSON()
call is a table with columnskey
,value
andtype
. In your case thekey
column contains the index of the element in the specified JSON array and thevalue
column contains a JSON object.Sample data:
Statement:
As an additional note, as @AlwaysLearning already commented, the reason for the error is that using a variable as the value of path in the
JSON_QUERY()
is supported in SQL Server 2017+. For these versions, you may use the following statement: