Determining SQL Server Version Number

by Warlock on Aug.03, 2009, under SQL

I’ve recently had to write some conditional SQL depending on which version of SQL Server I was running on.

This MSDN article shows that for modern versions of SQL Server, the following will get the full version number:

SELECT SERVERPROPERTY('productversion');

The problem with this is that it is in a string format (FYI you will need to cast it to VARCHAR), and it uses nested decimal notation (e.g. 10.0.1600.22 for SQL Server 2008). This format is very difficult to reason with, as what I am looking to do is conditionally execute SQL for SQL Server 2000 and for everything else execute some other SQL. I don’t care about minor revisions or service packs. To my knowledge, Microsoft does not provide any functions to work with nested decimals.

To make things easier, I constructed the following SQL to pull the major version number out of the string, convert it to an integer, and stick it in a variable:

DECLARE @MajorVersion int
SELECT  @MajorVersion = CAST(substring(CAST(SERVERPROPERTY('productversion') AS VARCHAR), 0, Charindex('.', CAST(SERVERPROPERTY('productversion') AS VARCHAR))) AS int);

Messy, I know. If anyone else has a better method, please leave it in the comments.

:,

2 Comments for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...