如何:指定预先部署或后期部署脚本How to: Specify Predeployment or Postdeployment Scripts

预先部署和后期部署脚本在从数据库项目生成的主部署脚本之前和之后执行 Transact-SQL 语句。Pre-deployment and post-deployment scripts execute Transact-SQL statements before and after the main deployment script, which is generated from the database project. 一个项目只能有一个预先部署脚本和一个后期部署脚本。A project can have only one pre-deployment and one post-deployment script. 这些脚本可用于许多用途。These scripts can be used for many purposes. 例如:For example:

  • 预先部署脚本可以从要更改的表中将数据复制到一个临时表,然后重新设置数据格式并在后期部署脚本中将数据应用于已更改表。A pre-deployment script can copy data from a table that is being changed into a temporary table before re-formatting and applying the data to the changed table in a post-deployment script,

  • 您可以将必须在某个表中存在的引用数据插入后期部署脚本中。You can insert reference data that must exist in a table in a post-deployment script. 在插入数据前,您可以测试此表是否已包含数据。Before you insert the data, you can test whether the table already contains data. 如果此表不为空,则必须清除现有数据或指定希望始终在部署数据库之前重新创建此数据库。If the table is not empty, you must clear the existing data or specify that you want to always re-create the database before you deploy it. 您可以将如下语句添加到后期部署脚本中:You can add a statement such as the following to your post-deployment script:

IF (EXISTS(SELECT * FROM [dbo].[MyReferenceTable]))  
BEGIN  
    DELETE FROM [dbo].[MyReferenceTable]  
END  

添加和修改预先部署或后期部署脚本To add and modify a pre- or post-deployment script

  1. 在“解决方案资源管理器” 中,展开数据库项目以便显示“脚本”文件夹。In Solution Explorer, expand your database project to display the Scripts folder.

  2. 右键单击“脚本”文件夹并选择“添加”。Right click on the Scripts folder and select Add.

  3. 从上下文菜单中选择“脚本”。Select Scripts in the context menu.

  4. 选择“预先部署脚本”或“后期部署脚本”。Select Pre-Deployment Script or Post-Deployment Script. 可以选择指定一个非默认名称。Optionally, specify a non-default name. 单击“添加”以便完成。Click Add to finish.

  5. 在“脚本”文件夹中双击该文件。Double click the file in the Scripts folder.

    Transact-SQL 编辑器将打开,并且显示该文件的内容。The Transact-SQL editor opens, displaying the contents of the file.

您可以在脚本中使用 SQLCMD 语法和变量,并且在数据库项目属性中设置它们。You can use SQLCMD syntax and variables in your scripts and set these in the database project properties. 例如:For example:

  • 您可以使用 SQLCMD 语法在预先部署或后期部署脚本中包含某一文件的内容。You can use SQLCMD syntax to include the content of a file in a pre- or post-deployment script. 文件将被包含并且按照您定义的顺序运行::r .\myfile.sqlFiles are included and run in the order you define them: :r .\myfile.sql

  • 您可以使用 SQLCMD 语法在后期部署脚本中引用某一变量。You can use SQLCMD syntax to reference a variable in the post-deployment script. 您在项目属性或发布配置文件中设置 SQLCMD 变量:You set the SQLCMD variable in the project properties or in a publish profile:

    :setvar TableName MyTable  
    SELECT * FROM [$(TableName)]  
    

有关如何在脚本中使用 SQLCMD 的详细信息,请参阅数据库项目设置For more information on using SQLCMD in scripts see Database Project Settings.

另请参阅See Also

面向项目的脱机数据库开发Project-Oriented Offline Database Development