Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL OPENJSON path as variable

declare @Path as nvarchar(100) 
set @path = '$.path.to."sub-object"'

DECLARE @json NVARCHAR(4000) = N'{  
      "path": {  
            "to":{  
                 "sub-object":["en-GB", "en-UK","de-AT","es-AR","sr-Cyrl"]  
                 }  
              }  
 }';

SELECT [key], value
FROM OPENJSON(@json, @Path)

I got error:

Incorrect syntax near '@Path'.

how to declare @path that i can change it.

like image 587
Mindaugas Petruškevičius Avatar asked Jan 29 '23 20:01

Mindaugas Petruškevičius


1 Answers

Passing path as variable to OPENJSON is available from SQL Server 2017 (aka vNext):

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

declare @Path as nvarchar(100) 
set @path = '$.path.to."sub-object"'

DECLARE @json NVARCHAR(4000) = N'{  
      "path": {  
            "to":{  
                 "sub-object":["en-GB", "en-UK","de-AT","es-AR","sr-Cyrl"]  
                 }  
              }  
 }';

SELECT [key], value
FROM OPENJSON(@json, @Path);

DbFiddle Demo

like image 141
Lukasz Szozda Avatar answered Feb 03 '23 06:02

Lukasz Szozda