如何通过 SQL 查询来检查是否有 JSON 函数?

How to check are there JSON Functions by SQL query?

JSON Function in SQL 2016如JSON_VALUE、JSON_QUERY等

我想在我的查询中使用它,但我仍然有旧服务器 SQL 2014,例如,不允许使用新功能。

我可以通过查询查看有没有JSON_VALUE这样的功能?像

IF operator_exists('JSON_VALUE')
    SELECT JSON_VALUE([Value], '$.MyPath')
      FROM [dbo].[MyTable] 
      WHERE [Name] = 'MyProperty'
ELSE
    SELECT ''

谢谢。

更新

如果我这样使用 ckecking(感谢 Rigerta Demiri)

DECLARE @compatibility_level int
SELECT @compatibility_level= compatibility_level FROM sys.databases WHERE name = 'MyDbName'
IF (@compatibility_level >= 130)
BEGIN
    SELECT JSON_VALUE([Value], '$.MyPath')
    FROM [dbo].[MyTable] 
    WHERE [Name] = 'MyProperty'
END
    SELECT 'not allowed'

...我收到以下 SQL 异常(在 2014 SQL Studio 上):

'JSON_VALUE' is not a recognized built-in function name

可能是 2014 MSSQL 解释器试图解析 所有代码块 并且无法理解什么是 JSON_VALUE

因为它取决于您安装的 SQL Server 的版本,并且由于您有不同的实例(甚至比 SQL Server 2016 更旧的实例),您可以检查兼容性级别是否您尝试查询的数据库等于 130。

您可以执行以下操作:

declare @compatibility_level int
select @compatibility_level= compatibility_level from sys.databases where name = 'TestDB'

if (@compatibility_level >= 130)
begin
declare @jsoninfo nvarchar(max)

set @jsoninfo=N'{  
     "info":{    
       "type":1,  
       "address":{    
         "town":"bristol",  
         "county":"avon",  
         "country":"england"  
       },  
       "tags":["sport", "water polo"]  
    },  
    "type":"basic"  
 }'  

select json_value(@jsoninfo,'$.info.address.town')  as town
end

The OPENJSON function is available only under compatibility level 130 (or higher).

您可以在 documentation.

中阅读

EDIT:

你得到的结果发生了,因为显然 "SQL Server doesn't know or care which branch of a conditional will be entered; it validates all of the statements in a batch anyway." 如本 post 的答案所述:T-Sql appears to be evaluating “If” statement even when the condition is not true

因此,解决方法是将整个语句创建为动态字符串。 像这样:

declare @compatibility_level int
select @compatibility_level= compatibility_level from sys.databases where name = 'TradingDWH'
if (@compatibility_level >= 130)
    begin

    declare @sql nvarchar(max);
    set @sql = ' declare @jsoninfo nvarchar(max) ' + ' set @jsoninfo=N''{ "info":{' + ' "type":1, "address":{ "town":"bristol", "county":"avon", "country":"england" }, "tags":["sport", "water polo"] }, "type":"basic" }'
    set @sql = @sql + 'select json_value(@jsoninfo,''$.info.address.town'')  as town'
    select @sql
    --exec sp_executesql @sql

    -- or your own query, like this:
    declare @sql2 nvarchar(max);
    declare @MyProperty nvarchar(100) = 'YourProperty'

    set @sql2 = ' SELECT JSON_VALUE([Value], ''$.MyPath'') '
    set @sql2 = @sql2 + 'FROM [dbo].[MyTable] WHERE [Name] = @MyProperty '
    select @sql2 
    --exec sp_executesql @sql2, N'@MyProperty nvarchar(100)', @MyProperty

    end
else 
begin 
    select 'Version prior to 130!' as [message]
end 

您可以阅读更多关于动态 SQL 的众多资源之一是 Don’t Fear Dynamic SQL