Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Although making each DDL script 'rerunnable' with IF NOT EXISTS etc is good practice, I can see how that approach will eventually get messy and cumbersome. It can also get especially thorny when you are running data conversion scripts.</p> <p>The approach I have always taken is to number each script sequentially and store them somewhere and keep track of the ID of last run script; that ID is your DBVersion. The DBVersion number is stored in a settings or version table in the DB. </p> <p>All that's left is to have some process for comparing the DBVersion value with the MAX(id) of your scripts table (or file, or dictionary or whatever) </p> <pre><code>CREATE TABLE DBVer ( DBVer INT PRIMARY KEY CLUSTERED ) INSERT INTO DBVer(DBVer) SELECT 1 CREATE TABLE DBScripts ( ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED, Script NVARCHAR(MAX) ) CREATE PROC UpdateDB AS DECLARE @i INT, @max INT, @SQL NVARCHAR(MAX) SELECT @max = MAX(ID), @i = MAX(DBVER) FROM DBScripts CROSS JOIN DBVer --only ever one row in here but make sure! if @i&gt;@max RETURN --no updates, let exit early WHILE @i &lt;= @max --loop through and apply new scripts BEGIN SELECT @SQL = Script FROM DBScripts WHERE ID = @i EXEC sp_executesql @statement = @SQL SET @i = @i + 1 END UPDATE DBVer SET DBVer = @i --this can also be in the loop GO </code></pre> <p>This is not a total solution but you get the general idea. </p> <p>Things to think about include where the update is getting called from if each of 100 clients call updateDB on startup it may be worth putting in some locking or some other means to manage a potential race condition. It may also be worth wrapping everything in a transaction. DDL can be rolled back but you can also fill up the log very quickly with big changes. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload