SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 

A Better Way To Script Database Objects

Photo by Andy Beales on Unsplash

Happy New Year! My New Year’s resolution for 2018 is to help you become a better SQL developer.

I want to start off with that today by showing you a much better way to generate database object change scripts.

Prefer video?  Watch this week’s post on YouTube instead!

If you are like I used to be for YEARS, anytime you want to copy a table, index, etc… you probably right click on that object in SQL Server Management Studio and click “Script <Table|Index|View|etc…> as” > “CREATE To”:

An inefficient way of generating change scripts

This is a pretty easy way to quickly script database objects, however it’s incomplete.

For starters, I’m forced to generate the scripts for tables one at a time.  Not fun.

Additionally, if I want to script associated objects for that table, like indexes, I have to go to each index and then right-click and select “Script Index as”.  Ugh.

There Is A Better Way

Instead of using “Script Table as”, you can right click on your database and choose “Tasks” > “Generate Scripts…”:

This option brings up a GUI that will allow you to script multiple objects at the same time:

Look ma, multiple objects at once!

Additionally if you click the “Advanced” button in the final page of the dialog, you will receive many more options for how your objects will get scripted, including the ability to script out the indexes!

Ooooooo, ahhhh – everything scripted in one fell swoop!

Using the Generate Scripts Task it’s easy to generate table, index, stored procedure, etc… change scripts all in one step – nice!

NOTE: If your SQL User receives an error when trying to generate the scripts, make sure they have the following access:

USE [MyDatabase]
GO

GRANT VIEW DEFINITION TO [MyUser]
GO

GRANT SELECT ON sys.sql_expression_dependencies TO [MyUser]
GO

Thanks for reading. You might also enjoy following me on Twitter.

Bert Wagner

Bert Wagner is a Business Intelligence Developer at Progressive Insurance. He enjoys solving challenging data transformations with T-SQL and optimizing for query performance. In addition to BI development, Bert loves building ASP.NET MVC web apps and building Internet of Things projects.

Comments

Leave a comment on the original post [bertwagner.com, opens in a new window]

Loading comments...