Import database with SSDT programmatically

偶尔善良 提交于 2019-12-12 03:26:19

问题


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?


回答1:


SSDT is powered by a library called the Data-Tier Application Framework (also known as DacFX). DacFX is a public API that you can use to extract and publish dacpac files. You can find a copy of DacFX in Program Files under Visual Studio or SQL Server in a directory something like this:

  • C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\130
  • C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin

You can download the latest version of DacFX here: https://www.microsoft.com/en-us/download/details.aspx?id=51672

Note that when you install DacFX it's also necessary to install its dependencies, SqlSysClrTypes and SqlDom, which can be found in the System Requirements section of the above download page.

To use DacFX to extract and publish a dacpac file, you can use SqlPackage.exe, like so:

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

Alternately, you can use DacFX programmatically using the Microsoft.SqlServer.Dac API, like so: 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"); } } }




回答2:


You could do it programatically but I would say the easiest would be to buy a license for redgate sqlcompare and using the command line version of that.




回答3:


Database Create Script

[2]: Run this Script in code

I hope It Help



来源:https://stackoverflow.com/questions/36474036/import-database-with-ssdt-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!