简体   繁体   English

SQL Server客户端数据库升级脚本问题

[英]Problem with SQL Server client DB upgrade script

SQL Server 2005, Win7, VS2008. 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 ): 我正在尝试执行以下操作(以下SQL脚本)并收到错误消息(在没有数据库的计算机上运行时):

Database 'MyDatabase' does not exist. 数据库“ MyDatabase”不存在。 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 ? 是否存在编写create / upgrade的更好方法?

SQL code: SQL代码:

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. 而是以外部方式提供它或对SQL进行预处理,以使用实际数据库的名称替换$$DATABASENAME$$令牌。

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. 您将无法在脚本中包含USE [MyDatabase] ,因为如果数据库不存在,则查询将无法解析。

Instead, what you can do is keep 2 separate scripts, one for an upgrade and one for a new database. 相反,您可以做的是保留2个单独的脚本,一个用于升级,一个用于新数据库。 Then you can call the scripts within the IF branches through xp_cmdshell and dynamic SQL. 然后,您可以通过xp_cmdshell和动态SQL在IF分支中调用脚本。 The following link has some examples that you can follow: 以下链接包含一些示例,您可以遵循:

http://abhijitmore.wordpress.com/2011/06/21/how-to-execute-sql-using-t-sql/ 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. PowerShell也可以使此任务更容易,但是我没有使用它的直接经验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM