Search code examples
sql-serverdatabaseimportsqlpackagebacpac

Import bacpac database with SqlPackage, check exist and specify location


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?


Solution

  • 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.