T-SQL OPENJSON路径作为变量

时间:2017-08-07 13:12:46

标签: sql-server json tsql

[NotMapped]
public IEnumerable<Activity> OrderedEntries
{
    get { return _entries.OrderBy(e => e.StartTime); }
}

我收到了错误:

  

'@Path'附近的语法不正确。

如何声明我可以更改它的@path。

2 个答案:

答案 0 :(得分:4)

将路径作为变量传递给OPENJSON,可从SQL Server 2017(又名vNext)获取:

  

在SQL Server 2017和Azure SQL数据库中,您可以提供变量作为路径值。

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

答案 1 :(得分:3)

有趣的是,您似乎在关注此链接:https://docs.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql

这在内联完成时有效:

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

SELECT [key], value
FROM OPENJSON(@json, '$.path.to."sub-object"')

当您对变量的引用进行更改时,它不会:

declare @Path as nvarchar(128)  = '$.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)

更新了一种黑客,但它有效

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

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

DECLARE @SQL NVARCHAR(MAX) = 
'SELECT [key], value
FROM OPENJSON(''' + @json + ''', ''' + @Path + ''')'

EXEC sp_executesql @Sql