0

I am using SQL Server 2016.

While this works fine:

SELECT JSON_VALUE(N'[{"FieldName":"xyz"}]', N'strict $[0]."FieldName"')

This retruns an error:

DECLARE @x nvarchar(100)
SET @x =N'0'

SELECT JSON_VALUE(N'[{"FieldName":"xyz"}]', N'strict $['+@x+']."FieldName"')

SELECT JSON_VALUE(N'[{"FieldName":"xyz"}]', N'strict $[sql:variable(@x)]."FieldName"')

Error:

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

How can I solve this?

1
  • 1
    The sql:variable() syntax is not supported in any version; this only works for XML queries. Commented Sep 29, 2020 at 7:36

1 Answer 1

1

You need to use SQL Server 2017+. As is mentioned in the documentation, in SQL Server 2017 (14.x) and in Azure SQL Database, you can provide a variable as the value of path. But even then, I don't think that N'strict $[sql:variable(@x)]."FieldName"' is a valid path expresison for a JSON_VALUE() call.

Working example for SQL Server 2017+:

DECLARE @x nvarchar(100)
SET @x = N'0'

SELECT JSON_VALUE(N'[{"FieldName":"xyz"}]', N'strict $[' + @x + ']."FieldName"')

For SQL Server 2016 you may try the following:

DECLARE @json nvarchar(100) = N'[{"FieldName":"xyz"}]'
DECLARE @x nvarchar(100) = N'0'

SELECT JSON_VALUE([value], '$.FieldName')
FROM OPENJSON(@json) j1
WHERE [key] = @x
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.