SQL Server Database schema versioning and update

6.8k views Asked by At

For my application I have to support update scenarios and the database might be affected.

I want to be able to update from an old version to the newest without installing intermediate versions. E.g. Suppose I have version A (the oldest), B (intermediate) and C (new version). I want to be able to update version A straight to version C. For the application files this is simple, I just replace the old with the new ones. However for the database I do not wish to generate a SQL Script to change the database schema from A straight to C, instead I want first apply a script to change the schema from A to B and from B to C.

How can I store the database version for a SQL Server database? Is there any special property which I can set, instead of implementing a version table? In my code (.NET) I want to read the database version and accordingly to execute the update SQL scripts in the proper order.

I will use both SQL Server 2005 and SQL Server 2008.

5

There are 5 answers

0
Remus Rusanu On BEST ANSWER

I use database extended properties, see Version Control and your Database:

SELECT [value] 
    from ::fn_listextendedproperty (
        'MyApplication DB Version', 
        default, default, default, default, default, default);

...

EXEC sp_updateextendedproperty 
    @name = N'MyApplication DB Version', @value = '1.2';
GO
0
Bravax On

This depends on your version of SQL Server you're using.

I don't believe a database version is a built in property of a database, however you can probably use an extended property.

Personally, I'd create my own version table, as this will allow you to associate more metadata with it.

0
Murph On

Stick a version table in, its simple, its effective, and for the past, erm, well its more than 10 years it has worked a treat for me.

I wrote this up in response to another question here

0
Zoran Horvat On

You can add a table which registers current version. Then run all upgrade scripts but scripts should be written in such way that they do not execute if current version is higher than version expected by the script.

In that way, it is irrelevant what is the current version of the database schema. Scripts will make only changes that were not already made to the schema.

Here you can find some stored procedures that significantly reduce effort writing upgrade scripts: How to Maintain SQL Server Database Schema Version

0
Ali Poustdouzan On

I prefer use plain SQL query for SQL schema migration and i'm not a fan of EF code first but it's not easy if you don't have a database version control, If you use .net there is a NuGet Package which is free and will control your database version and it work with plain SQL query.

https://www.nuget.org/packages/SQLMigrationByQuery