sql-serverdatabasevisual-studio-2010database-deployment

Visual Studio 2010 SQL Server 2008 Database Project - Custom Updates


In Visual Studio, say you've got a SQL 2008 Database Project and you add a non-nullable column to a table. When you go to deploy the database now, if that table has data in it it should fail. (Right?) How would you write custom logic so that during the update you can set this column to "x" or use a more advanced query or cursor to update the entire table and fill in the new column? This is something you would only want to happen once - at the same time the column was added to the database. Is there any support for this?


Solution

  • Here's what I ended up doing.

    1. Add version info to the database (e.g. in a SystemSettings table).
    2. Create a script for the next version (e.g. 1.1.0.0.sql).
    3. In the Scripts\Post-Deployment\Script.PostDeployment.sql file, add the following:

    DECLARE @versionMajor INT;
    DECLARE @versionMinor INT;
    DECLARE @versionBuild INT;
    DECLARE @versionRevision INT;

    SELECT TOP 1
        @versionMajor = VersionMajor,
        @versionMinor = VersionMinor,
        @versionBuild = VersionBuild,
        @versionRevision = VersionRevision
    FROM SystemSettings;

    IF (@versionMajor <= 1 AND @versionMinor < 1)
    BEGIN
    :r "..\Upgrade\1.1.0.0.sql"
    END

    This will run the 1.1.0.0 script if the database version is lower. The 1.1.0.0 script updates the database version numbers as its final step. Future updates simply require you to add another IF block.