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

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Stored procedure to script tables, has many options

By Gokhan Varol,

Both procedures are created in master database as system object so that they can be called from current database context.
There is quite a bit options I created please eyeball them.
The procedure uses READ UNCOMMITTED transaction level, I created it this way since our environment has a lot of DDL activity and every other tool gets lock timeout errors including management studio.
For partitioned tables the script gets the definition from the first partition.
The tables can be filtered by
a-) objectname (schema.tablename) this is default
b-) schema, table (input parameter is a valid like syntax, null means no filter)
c-) a TableList xml input which takes tablename or schemaname either of them can be null which means no filter

There is no cursor or looping, all tables can be scripted within one batch and usually within a second.
The procedure is using a string concat clr function, the code and compiled assembly is below. It assumed the clr aggregate is created in Util database (hardcoded in sp_scriptmain procedure).
When @PrintSQL parameter is set the output sql will be outputted as XML overcome, Management studio lets you print out up to 2GB in grid mode. The procedure can also return the sql statement as an output or can execute the SQL statement.


-- samples
-- script Humanresources.Employee Table
EXEC sp_script 'Humanresources.Employee'

-- script all tables
EXEC sp_script

-- script tables in schema like %dbo%
EXEC sp_script @SchemaName = '%dbo%'

-- script tables like %test% in schema dbo
EXEC sp_script @SchemaName = 'dbo', @TableName = '%test%'


Total article views: 2299 | Views in the last 30 days: 1
Related Articles

Create procedure and filter the result

Create procedure and filter the result


Generate Drop / Create Script for views, stored Procedures

This Script generates drop and create scripts for views or stored procedures.


script to create indexes existing in a database

script to create indexes existing in a database


Database Snapshot Create/Drop/Restore SQL Script.

Database Snapshot Creat/Drop/Restore SQL Script for Single or multiple data files of databases.


Creating a Script from a Stored Procedure

Ryan demonstrates how he arrived at a solution that allows you to create scripts from a stored proce...

check constraints    
foreign keys (fk)    
primary key (pk)