如何生成sql脚本来更新现有数据库并保留其数据

Jed*_*Jed 1 sql-server scripting wizard

我有一个包含数据的SQL Server 2008数据库(称之为productionDB),将在生产环境中使用.

我有一个在临时环境中使用的另一个SQL Server 2008数据库(称为stagingDB).

我正在开发的应用程序继续发展,以至于我经常对数据库模式进行更改(即添加/编辑表和添加/编辑存储过程).

到目前为止,每次我对stagingDB进行更改时,我都会生成脚本(通过SQL Server脚本向导),这些脚本将删除/创建所有模式.因此,当我在productionDB上运行脚本时,它会成功更新到更新的模式,但是生产数据库中的所有数据都将丢失 - 这一直很好,直到现在.

接下来,我想生成脚本,将现有数据保存在productionDB中并更新其架构.

我无法在SQL Server脚本向导中找到可以执行我所描述的选项.

SQL Server脚本向导是否能够满足我的需求?如果是这样,怎么样?

Kei*_*thS 6

删除/重新创建是一把大刀; 你必须更多手术.以下是一些伪代码示例:

添加新列:

if not exists (select your column from syscolumns)
   alter yourTable add
      yourColumn (type) NULL
Run Code Online (Sandbox Code Playgroud)

如果它不能为空,请设置默认值,或更新列以填充数据,然后更改表并将列设置为NOT NULL.

重命名列:

if not exists (select your column from syscolumns)
begin
   alter yourTable add yourColumn <type> NULL

   update yourTable set yourColumn = oldColumn

   alter yourTable drop oldColumn
end
Run Code Online (Sandbox Code Playgroud)

重命名表格:

if not exists (select your table from sysobjects)
begin
   create yourTable
       <your columns here>

   insert into yourTable ( <columns> ) select ( <columns> ) from oldTable

   delete from oldTable
   drop table oldTable
end
Run Code Online (Sandbox Code Playgroud)

注意一个共同的主题; 首先,您必须通过检查是否存在更新的架构元素来检查您是否已执行此更新.然后,按添加模式 - >迁移数据 - > drop schema的顺序添加或删除必要的内容.这需要更多的代码工作,但它会更快地运行并保存您的数据.