Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - how to "Generate and Publish Scripts" automatically

I want to automatically (ideally from the command prompt in a batch file) automate the generation of the schema of my SQL Server 2008 R2 database.

In SSMS, I can right-click the DB, choose "Tasks", "Generate scripts", and then follow the wizard to gen a Schema script. Is there a command-line version of this process that I can use?

like image 280
Matt Roberts Avatar asked Feb 21 '11 16:02

Matt Roberts


People also ask

How do I schedule a SQL Server generate script?

Open SQL Server Management Studio. In the Object Explorer, expand Databases, and then locate the database that you want to script. Right-click the database, point to Tasks, and then click Generate Scripts. In the Script Wizard, verify that the correct database is selected.

How do you generate create table script for all tables in SQL Server database?

Generate Database Script in SQL Server Now right-click the database then Tasks->Generate scripts. After that a window will open. Select the database and always check "script all objects in the selected database". It will generate a script for all the tables, sp, views, functions and anything in that database.

How do I turn on autocomplete in SQL?

Click the 'Complete Word' button on the Text Editor toolbar. In the Edit menu, point to IntelliSense, and then click 'Complete Word'.

How do I save a SQL Server database as a script?

Right-click on the database that should be exported. On the "Set Scripting Options" you can choose whether to save or publish the script. Once you customize all the desired save and advanced options, click the "Next >" button. Clicking the "Advanced" button would allow you to customize the exported content.


2 Answers

Microsoft released a new tool a few weeks ago called mssql-scripter that's the command line version of the "Generate Scripts" wizard in SSMS. It's a Python-based, open source command line tool and you can find the official announcement here. Essentially, the scripter allows you to generate a T-SQL script for your database/database object as a .sql file. You can generate the file and then execute it. This might be a nice solution for you to generate the schema of your db (schema is the default option). Here's a quick usage example to get you started:

$ pip install mssql-scripter
# script the database schema and data piped to a file.
$ mssql-scripter -S localhost -d AdventureWorks -U sa  > ./adventureworks.sql

More usage examples are on our GitHub page here: https://github.com/Microsoft/sql-xplat-cli/blob/dev/doc/usage_guide.md

like image 70
Tara Raj Avatar answered Nov 03 '22 23:11

Tara Raj


From this answer, there appear to be tools called SMOScript and ScriptDB that can do that.

If you find a way without third party tools please share :)

like image 44
Andomar Avatar answered Nov 04 '22 01:11

Andomar