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?
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
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 :)
Related
I tried to generate the script by query because I want create easily and same settings. I checked MSdoc but there is no method.
I use SSMS v17.6, SQLServer2016(SP2) on WindowsServer2012 R2 Standard.
By the GUI, DB right click=>Task=>generate scripts=>select database objects and set some settings.
I want to generate by query.
You can follow below steps to automate the creation of a database.
First export the database as a dapac using Export Data Tier Application
Install SQLPackage.exe in the environment where you are planning to carry out the deployment. You can download sqlpackage.exe download path . It will be used to automate the generation of scripts from DACPAC.
Once you have the DACPAC of the database, you can publish the same to any environment. The caveat is, Sqlpackage.exe generates incremental script, comparing against the target datatbase. If you want complete CREATE script, then you can point against any empty database or system database like master to generate incremental CREATE scripts(here it will be complete database script, as target is empty database). The generated script will be present in the output path (here, it is C:\temp)
Note: we are setting parameter (DropObjectsNotInSource to false), to avoid generation of drop objects of the target database, which are
missing in source DACPAC.
"<Path>\SqlPackage.exe"
/Action:script
/SourceFile:“<Path>\Database.dacpac”
/TargetDatabaseName:master
/TargetServerName:"localhost"
/OutputPath:C:\temp
/p:DropObjectsNotInSource:false
UPDATE
I see that, now there is a tool mssql-scripter(currently in preview) to carry out the same activity of Generate Scripts wizard of SQL Server Management Studio. You can see about the tool here: https://github.com/Microsoft/mssql-scripter
I'm using forms authentication to handle users and attempting to deploy my database to SQL Azure, but getting this error message:
The only table of the four listed that I utilize is aspnet_Membership, and the only other table I use is aspnet_Users from implementing forms authentication. What is TextInRowSize and why does SQL Azure care about it? Do I have any option to modify aspnet_Membership to make it compatible?
If it would be easier to remove the current system altogether and replace it with my own, I'm fine with that too.
That looks like an error in the data-tier application framework. I can suggest a workaround to get your database to Azure:
Use SqlPackage.exe (https://msdn.microsoft.com/en-us/library/hh550080(v=vs.103).aspx) from the command line to extract a dacpac file with all table data. Then use SqlPackage.exe to deploy that dacpac file to your database in Azure. The extract command would look something like:
C:\>"c:\Program Files\Microsoft SQL Server\120\DAC\bin\SqlPackage.exe" /a:extract /scs:"Data Source=yourSqlServer;Integrated Security=true;Initial Catalog=yourDatabase" /tf:C:\temp\mydatabase.dacpac /p:ExtractAllTableData=true
And the import command would look something like:
C:\>"c:\Program Files\Microsoft SQL Server\120\DAC\bin\SqlPackage.exe" /a:publish /tcs:"Data Source=yourAzureSQLServer.database.windows.net;User Id=yourUserId;Password=yourPassword;Initial Catalog=yourDatabase" /sf:C:\temp\mydatabase.dacpac
So quick suggestions since I see you are using V12 which should support those properties now.
First make sure you are using SSMS 2014 SP1 at least, this has a number of fixes for using V12. Secondly make sure you install the May 2015 update to DacFX (which is the program that creates bacpac files) you can install it here: http://www.microsoft.com/en-us/download/details.aspx?id=46898
This should get you to the best possible chance of your import/export working.
This was solved by generating a SQL Azure script for the DB, and running it on Azure. Here's how I solved it:
First, open SQL Server, right click the database you want to transfer and click "Tasks > Generate Scripts..."
Next, click "Advanced" on the scripting options panel and find the row "Script for the database engine type." Select "Windows Azure SQL Database" and click OK (Note: if you have data that you want to transfer as well, choose "Schema and Data" from the "Types of data to script" option).
Proceed thru the rest of the script generation dialog, remembering where you saved the script file. Connect to your database server using SQL Server or windowsazure.com. Generate a new query for your new database, enter the script that was generated by SQL Server and execute.
Seems like TextInRowSize stores large data for older SQL Server types such as text and ntext. You would need to change it's type to nvarchar(max).
Here's a link to a more detailed explanation.
http://www.dnnsoftware.com/wiki/unsupported-property-textinrowsize-set-and-is-not-supported-when-used-as-part-of-a-data-package
Is it possible to generate sql scripts for my sql server 2005/8 database via the command line?
I want to automate the build process and part of it requires me to get the entire schema (tables/sprocs/etc) in a file.
Microsoft released a new tool last week called mssql-scripter. The tool is a Python-based, open source command line tool and you can find the official announcement here. Essentially, the scripter allows you to generate T-SQL scripts (DDL and DML) for your database/database object as a .sql file. It's the command line version of the 'Generate Scripts' wizard in SSMS. Here's a quick usage example to get you started (schema only is the default):
$ 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
There used to be an utility called SCPTXFR.EXE which was part of the standard SQL Server 7.0 and 2000 install.Its original purpose was as part of the upgrade process that allowed SQL Server 6.5 databases to be migrated to SQL Server 7.0 and 2000. However it is also very useful in a day-to-day environment, as it allows you to programmatically generate scheduled scripts of database objects.
Not sure if this will work for SQL 2005/2008. Check this document for full details of this utility.
Raj
I had to do something similar in a past project. I wrote a simple C# console application using Sql Server Management Objects. You can write code as simple as this (may need some tweaking):
Server myServer = new Server("name");
Database db = myServer.Databases["name"];
foreach (StoredProcedure sp in db.StoredProcedures)
{
File.WriteAllText(sp.Name, sp.TextBody);
}
I wrote a utility for this task, SMOscript.
It's based on the principle of SCPTXFR (which Raj mentioned), and also supports the new object types in SQL 2005 and 2008. Script generation is performed by the SMO library.
Powershell script + object Microsoft.SqlServer.Management.Smo.Scripter? See http://blogs.msdn.com/buckwoody/archive/2009/07/02/powershell-and-sql-server-script-all-tables.aspx for an example showing how to get started w/tables. You'd have to extend the idea to other objects.
I'd like to automate the script generation in SQL Server Management Studio 2008.
Right now what I do is :
Right click on my database, Tasks, "Generate Scripts..."
manually select all the export options I need, and hit select all on the "select object" tab
Select the export folder
Eventually hit the "Finish" button
Is there a way to automate this task?
Edit : I want to generate creation scripts, not change scripts.
SqlPubwiz has very limited options compared to the script generation in SSMS. By contrast the options available with SMO almost exactly match those in SSMS, suggesting it is probably even the same code. (I would hope MS didn't write it twice!) There are several examples on MSDN like this one that show scripting tables as individual objects. However if you want everything to script correctly with a 'full' schema that includes 'DRI' (Declarative Referential Integrity) objects like foreign keys then scripting tables individually doesn't work the dependencies out correctly. I found it is neccessary to collect all the URNs and hand them to the scripter as an array. This code, modified from the example, works for me (though I daresay you could tidy it up and comment it a bit more):
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Sdk.Sfc;
// etc...
// Connect to the local, default instance of SQL Server.
Server srv = new Server();
// Reference the database.
Database db = srv.Databases["YOURDBHERE"];
Scripter scrp = new Scripter(srv);
scrp.Options.ScriptDrops = false;
scrp.Options.WithDependencies = true;
scrp.Options.Indexes = true; // To include indexes
scrp.Options.DriAllConstraints = true; // to include referential constraints in the script
scrp.Options.Triggers = true;
scrp.Options.FullTextIndexes = true;
scrp.Options.NoCollation = false;
scrp.Options.Bindings = true;
scrp.Options.IncludeIfNotExists = false;
scrp.Options.ScriptBatchTerminator = true;
scrp.Options.ExtendedProperties = true;
scrp.PrefetchObjects = true; // some sources suggest this may speed things up
var urns = new List<Urn>();
// Iterate through the tables in database and script each one
foreach (Table tb in db.Tables)
{
// check if the table is not a system table
if (tb.IsSystemObject == false)
{
urns.Add(tb.Urn);
}
}
// Iterate through the views in database and script each one. Display the script.
foreach (View view in db.Views)
{
// check if the view is not a system object
if (view.IsSystemObject == false)
{
urns.Add(view.Urn);
}
}
// Iterate through the stored procedures in database and script each one. Display the script.
foreach (StoredProcedure sp in db.StoredProcedures)
{
// check if the procedure is not a system object
if (sp.IsSystemObject == false)
{
urns.Add(sp.Urn);
}
}
StringBuilder builder = new StringBuilder();
System.Collections.Specialized.StringCollection sc = scrp.Script(urns.ToArray());
foreach (string st in sc)
{
// It seems each string is a sensible batch, and putting GO after it makes it work in tools like SSMS.
// Wrapping each string in an 'exec' statement would work better if using SqlCommand to run the script.
builder.AppendLine(st);
builder.AppendLine("GO");
}
return builder.ToString();
What Brann is mentioning from the Visual Studio 2008 SP1 Team Suite is version 1.4 of the Database Publishing Wizard. It's installed with sql server 2008 (maybe only professional?) to \Program Files\Microsoft SQL Server\90\Tools\Publishing\1.4. The VS call from server explorer is simply calling this. You can achieve the same functionality via the command line like:
sqlpubwiz help script
I don't know if v1.4 has the same troubles that v1.1 did (users are converted to roles, constraints are not created in the right order), but it is not a solution for me because it doesn't script objects to different files like the Tasks->Generate Scripts option in SSMS does. I'm currently using a modified version of Scriptio (uses the MS SMO API) to act as an improved replacement for the database publishing wizard (sqlpubwiz.exe). It's not currently scriptable from the command line, I might add that contribution in the future.
Scriptio was originally posted on Bill Graziano's blog, but has subsequently been released to CodePlex by Bill and updated by others. Read the discussion to see how to compile for use with SQL Server 2008.
http://scriptio.codeplex.com/
EDIT: I've since started using RedGate's SQL Compare product to do this. It's a very nice replacement for all that sql publishing wizard should have been. You choose a database, backup, or snapshot as the source, and a folder as the output location and it dumps everything nicely into a folder structure. It happens to be the same format that their other product, SQL Source Control, uses.
I wrote an open source command line utility named SchemaZen that does this. It's much faster than scripting from management studio and it's output is more version control friendly. It supports scripting both schema and data.
To generate scripts run:
schemazen.exe script --server localhost --database db --scriptDir c:\somedir
Then to recreate the database from scripts run:
schemazen.exe create --server localhost --database db --scriptDir c:\somedir
You can use SQL Server Management Object (SMO) to automate SQL Server 2005 management tasks including generating scripts: http://msdn.microsoft.com/en-us/library/ms162169.aspx.
If you're a developer, definitely go with SMO. Here's a link to the Scripter class, which is your starting point:
Scripter Class
I don't see powershell with SQLPSX mentioned in any of these answers... I personally haven't played with it but it looks beautifully simple to use and ideally suited to this type of automation tasks, with tasks like:
Get-SqlDatabase -dbname test -sqlserver server | Get-SqlTable | Get-SqlScripter | Set-Content -Path C:\script.sql
Get-SqlDatabase -dbname test -sqlserver server | Get-SqlStoredProcedure | Get-SqlScripter
Get-SqlDatabase -dbname test -sqlserver server | Get-SqlView | Get-SqlScripter
(ref: http://www.sqlservercentral.com/Forums/Topic1167710-1550-1.aspx#bm1168100)
Project page: http://sqlpsx.codeplex.com/
The main advantage of this approach is that it combines the configurablity / customizability of using SMO directly, with the convenience and maintainability of using a simple existing tool like the Database Publishing Wizard.
In Tools > Options > Designers > Table and Database Designers there's an option for 'Auto generate change scripts' that will generate one for every change you make at the time you save it.
You can do it with T-SQL code using the INFORMATION_SCHEMA tables.
There are also third-party tools - I like Apex SQL Script for precisely the use you are talking about. I run it completely from the command-line.
If you want to a Microsoft solution you can try: Microsoft SQL Server Database Publishing Wizard 1.1
http://www.microsoft.com/downloads/details.aspx?FamilyId=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en
It create a batch process you can run anytime you need to rebuild the scripts.
Try new SQL Server command line tools to generate T-SQL scripts and monitor Dynamic Management Views.
Worked for me like charm. It is a new python based tool from Microsoft that runs from command line.
Everything works like described on the Microsoft page (see link below)
Worked for me with SQL 2012 server.
You install it with pip:
$pip install mssql-scripter
Command parameter overview as usual with h for help:
mssql-scripter -h
Hint:
If you log in to SQL-Server via Windows authentication, just leave away Username and password.
https://cloudblogs.microsoft.com/sqlserver/2017/05/17/try-new-sql-server-command-line-tools-to-generate-t-sql-scripts-and-monitor-dynamic-management-views/
I've been using DB Comparer - Its free and no fuss script entire DB and can compare to another DB and also produce a Diff script . Excellent for Development to Production change scripts.
http://www.dbcomparer.com/
From Visual Studio 2008 SP1 TeamSuite :
In the Server Explorer / Data Connections tab, there's a publish to provider tool which does the same as "Microsoft SQL Server Database Publishing Wizard", but which is compatible with MS Sql Server 2008.
There is also this simple command line tool I build for my needs.
http://mycodepad.wordpress.com/2013/11/18/export-ms-sql-database-schema-with-c/
It can export an entire db, and it tries to export encrypted objects. Everything is stored in folders and separate sql files for easy file comparison.
Code is also available on github.
I am using VS 2012(for DBs on MSSQL Server 2008) compare database has an option to save it, the comparison and options. This is essentially what are your settings for delivery. After that you can do update or generate script.
I just find it it a little bit awkward to load it from file later(drag and drop from windows explorer) as I do not see the file in solution explorer.
Is it possible to somehow use a .bat file to script the schema and/or content of a SQL Server database?
I can do this via the wizard, but would like to streamline the creation of this file for source control purposes.
I would like to avoid the use of 3rd party tools, just limiting myself to the tools that come with SQL Server.
There is a free tool called SubCommander that is a part of the open source SubSonic software. I have successfully used this tool myself to create both schema and data "dumps" each night.
You can script out your schema and
data (and then version it in your
favorite source control system) using
SubCommander. Simply use the command
"version" and tell SubCommander where
to put the data:
sonic.exe version /out Scripts
This will output a script file (.sql)
to the local scripts directory of your
project
You can also try using the Microsoft SQL Server Database Publishing wizard, although i am not sure that you can use it in a bat file.