snippetsqlMinor
How can I query the SQL Server Compatibility Level into a variable?
Viewed 0 times
canthecompatibilitysqllevelqueryintohowservervariable
Problem
I know to query the current Compatibility Level of a database with
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.
declare @dbname sysname
select @dbname = db_name(0)
exec sp_dbcmptlevel @dbnameBut 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.
Solution
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
GO
-- for SQL 2000+
declare @level tinyint;
select @level = [cmptlevel]
from sysdatabases
where name = 'AdventureWorks'
Select @level
GOCode Snippets
-- for SQL 2005+
declare @level tinyint;
select @level = [compatibility_level]
from sys.databases
where name = 'AdventureWorks'
Select @level
GO
-- for SQL 2000+
declare @level tinyint;
select @level = [cmptlevel]
from sysdatabases
where name = 'AdventureWorks'
Select @level
GOContext
StackExchange Database Administrators Q#7299, answer score: 5
Revisions (0)
No revisions yet.