Can I run SqlPackage
to import bacpac
, which can check database exist before run, and also specify where to put the .mdf, .ldf
file? So when the database exist, it will not do anything; but if it is not existed, it will import the database for me?
Asked
Active
Viewed 1,192 times
2

chinh nguyen van
- 729
- 2
- 7
- 18
-
1I think you will have to combine T-SQL and sqlpackage.exe to achieve this. xp_cmdshell for sqlpackage.exe. – Dean Savović May 30 '17 at 10:53
-
@DeanSavović I tried your solution and it worked, thank :) – chinh nguyen van Jun 01 '17 at 09:08
1 Answers
2
SqlPackage.exe doesn't accept arguments to specify the location of the mdf and ldf files for the import action.
There are a couple of options to work around this:
- Create an empty database with the desired mdf and ldf files yourself (using, for example, sqlcmd), and then run SqlPackage.exe to import the bacpac file into the empty database.
- Use a "deployment contributor" to modify the behavior of deployment at runtime. This is a bit complicated as it involves compiling some C# code into a .NET dll that must then be used when performing the import operation. But the nice part is that you can rewrite the T-SQL that SqlPackage.exe executes however you'd like. Here's a sample deployment contributor that modifies the data and log file paths: https://github.com/Microsoft/DACExtensions/blob/master/Samples/Contributors/DbLocationModifier.cs
As for different behavior for exists vs doesn't exist -- note that the import command will refuse to modify a non-empty database, so it's safe to execute the import operation without regard to whether the database already exists.

Steven Green
- 3,387
- 14
- 17
-
I tried your suggestion for my Advanced Installer project and it worked, thanks – chinh nguyen van Jun 01 '17 at 09:10