有没有办法根据 SQL Server 版本执行 SQL 语句?

Dra*_*tic 5 index sql-server-2005 sql-server sql-server-2008-r2

如果 SQL Server 是 2008 或更新版本,我想在表上创建计算索引,如果 SQL Server 是 2005 或更新版本,我想创建一个简单索引:

-- check for sql server version
if (select cast(left(cast(serverproperty('productversion') as varchar), 4) as decimal(5, 3))) >= 10 
        CREATE unique nonclustered index ix1_table
            ON table (column1, column2)
            WHERE column1 is not null and column2 is not null
        ELSE
            CREATE nonclustered index ix1_table
                ON table (column1, column2)
Run Code Online (Sandbox Code Playgroud)

问题是整个语句都被评估了,在 SQL Server 2005 上这会引发错误:

关键字“WHERE”附近的语法不正确。

是否可以根据 SQL Server 版本以某种方式创建不同的索引?

小智 7

您可以使用动态 SQL

我的意思是先检查版本

然后使用字符串变量构建 SQL 语句,例如 nvarchar(max)

然后通过 sp_executeSQL 执行

我认为以下脚本可以用于此任务

-- check for sql server version
declare @sql nvarchar(max)
if (select cast(left(cast(serverproperty('productversion') as varchar), 4) as decimal(5, 3))) >= 10 

set @sql = N'CREATE unique nonclustered index ix1_table ON [table] (column1, column2)
        WHERE column1 is not null and column2 is not null'

        ELSE

set @sql = N'CREATE nonclustered index ix1_table ON [table] (column1, column2)'


exec sp_executeSQL @sql
Run Code Online (Sandbox Code Playgroud)


小智 5

正如您所猜测的,您的方法的问题在于查询语法,如果 SQL Server 版本不够高,则该语法被认为是无效的,从而导致整个查询被拒绝,即使该代码实际上永远不会被执行。

您可以使用“EXECUTE”(或“EXEC”)命令绕过此检查:

IF <Version Check>
    EXECUTE('Index creation command for SQL Server 2008')
ELSE
    EXECUTE('Index creation command for SQL Server 2005')
Run Code Online (Sandbox Code Playgroud)

'EXECUTE' 语句的参数没有事先评估正确性;只要到达该语句,它就会按原样执行(在运行时可能会产生错误)。

完整信息在这里