Home > SQL Server, T-SQL > Updating SQL Server compatibility_level Dynamically

Updating SQL Server compatibility_level Dynamically

My company is starting to look at upgrading to SQL Server 2012, so I’ve installed it on a server here and am working to get an application set up. I ran the Upgrade Advisor against the existing server, which is running SQL Server 2005. It errored on a number of databases because they were set to compatibility_level 80 and it can only processes 90 or higher. I put together a quick dynamic script to update the compatibility mode to 90 for anything set below that. In the spirit of Ted Krueger’s (b|t) post on throw-away SQL from last year, here’s the code:

USE master

-- Shut off 'row(s) affected' messages in your output making it easier to copy and paste dynamic SQL

-- Create a temp table to hold the list of database names
(dbname SYSNAME)

-- Declare your local variables
DECLARE @sqlstr VARCHAR(2000)

-- Get a list of database names that are online and in a compatibility mode less than 2005.  This can be adjusted to look for other compatibility_level values.
SELECT name FROM sys.databases
WHERE compatibility_level < 90
AND state_desc = 'ONLINE'

-- Get a count of those database names for a loop
SET @dbcount = @@ROWCOUNT
-- Initialize your loop counter
SET @loopcount = 1

-- While the loop counter is less than the count of databases, execute your loop
WHILE @loopcount <= @dbcount
	-- Get the top database name from the temp table
	SET @dbname = (SELECT TOP (1) dbname FROM #dbcomp)
	-- Build your ALTER DATABASE statement to update the compatibility_level
	SET @sqlstr = 'ALTER DATABASE ' + @dbname + ' SET COMPATIBILITY_LEVEL = 90;'
	/*PRINT @sqlstr - Uncomment if you want to print the SQL statement for future use*/
	-- Execute the ALTER DATABASE statement for each database
	-- Delete the TOP row from the temp table
	DELETE TOP (1) FROM #dbcomp
	-- Increment the loop counter
	SET @loopcount = @loopcount + 1


-- Clean up the temp table when done
DROP TABLE #dbcomp
Categories: SQL Server, T-SQL Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: