Feb 3, 2011

Stored procedure to script tables

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%'

No comments:

Post a Comment


Thanks for your visit to this blog.
We would be happy with your Queries/Suggestions.