HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Is there a way to execute SQL statement based on SQL Server version?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
statementsqlversionwaybasedserverthereexecute

Problem

I would like to create computed index on a table if SQL Server is 2008 or newer and a simple index if SQL Server is 2005 or older:

-- 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)


The problem is that the whole statement is evaluated and on SQL Server 2005 this throws an error:


Incorrect syntax near the keyword 'WHERE'.

Is it possible to somehow create different index based on SQL Server version?

Solution

You can use dynamic SQL

I mean first check the version

Then build your SQL statement using a string variable, for example nvarchar(max)

Then execute it by sp_executeSQL

I think following script can work for this task

-- 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

Code Snippets

-- 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

Context

StackExchange Database Administrators Q#57785, answer score: 8

Revisions (0)

No revisions yet.