开发者

Problem with SQL Server client DB upgrade script

SQL Server 2005, Win7, VS2008. I have to upgrade database from the old version of product to the newer one. I'd like to have one script that creates new database and upgrades old database to the new state. I am trying to do the following (SQL script below) and get the error (when running on machine with no database ):

Database 'MyDatabase' does not exist. Make sure that the name is entered correctly.

The question is:

  1. How can I specify database name in upgrade part
  2. Is the better way to write create/upgrade exists ?

SQL c开发者_如何学编程ode:

USE [master]

-- DB upgrade part
if exists (select name from sysdatabases where name = 'MyDatabase')
BEGIN
  IF (<Some checks that DB is new>) 
  BEGIN
    raiserror('MyDatabase database already exists and no upgrade required', 20, -1) with log
  END 
  ELSE
  BEGIN
    USE [MyDatabase]
    -- create some new tables
    -- alter existing tables
    raiserror('MyDatabase database upgraded successfully', 20, -1) with log
  END
END

-- DB creating part
CREATE DATABASE [MyDatabase];

-- create new tables


You don't usually want to explicitly specify database name in a script. Rather, supply it exernally or pre-process the SQL to replace a $$DATABASENAME$$ token with the name of an actual database.


You're not going to be able to include the USE [MyDatabase] in your script since, if the database doesn't exist, the query won't parse.

Instead, what you can do is keep 2 separate scripts, one for an upgrade and one for a new database. Then you can call the scripts within the IF branches through xp_cmdshell and dynamic SQL. The following link has some examples that you can follow:

http://abhijitmore.wordpress.com/2011/06/21/how-to-execute-sql-using-t-sql/

PowerShell may make this task easier as well, but I don't have any direct experience using it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜