Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I know to query the current Compatibility Level of a database with

declare @dbname sysname
select @dbname = db_name(0)
exec sp_dbcmptlevel @dbname

But this seems to return its result via print and I have found no way to assign the value to a variable and use it to control if ... else ... constructs to execute different code depending on current setting.

share|improve this question
up vote 5 down vote accepted

You could query the system table sys.databases:

-- for SQL 2005+
declare @level tinyint;
select @level = [compatibility_level]
from sys.databases
where name = 'AdventureWorks'

Select @level

-- for SQL 2000+
declare @level tinyint;
select @level = [cmptlevel]
from sysdatabases
where name = 'AdventureWorks'

Select @level
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.