I have a situation where I need to copy everything out of a database (except data) and deploy it to a new database. I am currently doing this by importing from the existing database into SSDT and then publish the project to the new database.
I want to know if there is a way I can do this programmatically. Ideally I would like to have a process in place where I can give the process the name of the database to copy from, the name of the database to copy to, and then the process would just automatically carry out the import and export.
What might be a good way to do this?
答案 0 :(得分:8)
SSDT由称为数据层应用程序框架(也称为DacFX)的库提供支持。 DacFX是一个公共API,可用于提取和发布dacpac文件。您可以在Visual Studio或SQL Server下的Program Files中找到DacFX的副本,其目录如下:
您可以在此处下载最新版本的DacFX: https://www.microsoft.com/en-us/download/details.aspx?id=51672
请注意,在安装DacFX时,还需要安装其依赖项SqlSysClrTypes和SqlDom,这些依赖项可以在上面的下载页面的“系统要求”部分找到。
要使用DacFX提取和发布dacpac文件,您可以使用SqlPackage.exe,如下所示:
C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin\SqlPackage.exe /a:extract /scs:"Data Source=YOURSERVER;Initial Catalog=YOURDB;Integrated Security=true" /tf:C:\temp\yourdb.dacpac
C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin\SqlPackage.exe /a:publish /tcs:"Data Source=YOURSERVER;Initial Catalog=YOUROTHERDB;Integrated Security=true" /sf:C:\temp\yourdb.dacpac
或者,您可以使用Microsoft.SqlServer.Dac API以编程方式使用DacFX,如下所示:
using Microsoft.SqlServer.Dac;
class Program
{
static void Main(string[] args)
{
DacServices ds = new DacServices("Data Source=YOURSERVER;Initial Catalog=YOURDB;Integrated Security=true");
ds.Extract(@"C:\temp\yourdb.dacpac", "YOURDB", "AppName", new System.Version());
using (DacPackage dp = DacPackage.Load(@"C:\temp\yourdb.dacpac"))
{
ds.Deploy(dp, "YOUROTHERDB");
}
}
}
答案 1 :(得分:1)
你可以以编程方式进行,但我会说最简单的方法是购买redgate sqlcompare的许可证并使用命令行版本。
答案 2 :(得分:0)