Thanks to .NET Core it is finally possible to generate SQL Server databases scripts from Linux (by using C#). For such tasks one usually had to use the SQL Server Management Studio (SSMS) from Microsoft - which doesn't run on Linux:
SQLServerScripter
needs to run on .Net Core 2.0
.
First install Microsoft .Net Core.
I recommend using the Docker image:
sudo docker pull microsoft/dotnet:2.0.0-sdk
Now clone this GitHub repository:
git clone git@github.com:mkurz/SQLServerScripter.git
Let's assume you cloned it into the folder /path/to/SQLServerScripter/
.
Let's say you want a script to be saved in the folder /path/to/output/folder/
. Start a docker container like this:
sudo docker run -it -v /path/to/SQLServerScripter/:/SQLServerScripter -v /path/to/output/folder/:/SQLScripts --rm microsoft/dotnet:2.0.0-sdk
Inside the container you can now run the SQLServerScripter
inside the /SQLServerScripter/
folder by calling:
dotnet run <datasource> <database> <username> <outputFolder>
The program will then prompt you for the database password. (The first run may take a couple of seconds because some dependencies have to be evaluated first)
For example:
cd /SQLServerScripter/
# Script the SQL Server database "Northwind" with user "Einstein" running on another docker container or the host via IP on port 1436:
dotnet run 172.17.0.5,1436 Northwind Einstein /SQLScripts/
# Script an Azure SQL Server database "Westwind" with user "DaVinci" running in the Azure cloud:
dotnet run someAzureDomain.database.windows.net Westwind DaVinci /SQLScripts/
If you have a look in the source code you will recognize that you can easily change the parameters for the generated script by changing the ScriptingOptions
properties.
Just FYI (but probably not relevant for you anyway):
The NuGet packages you see in /bin/nuget
were copied over from Microsoft's SQL Tools Service - which is (also) used in the Visual Studio Code mssql plugin.
The generated script should be UTF-8
encoded. However it seems some comments, etc. use Windows line breaks. You can convert the sql script to a unix file by running:
dos2unix myscript.sql