You are on page 1of 1

Building the Schema Documentation Solution

With a basic understanding of what we need to do, we should discuss the tools we will use
before diving in. One important component of this script is dynamic SQL.

Dynamic SQL
In order to efficiently gather metadata from a database whose name is not known until runtime,
we need to generate dynamic USE statements. The syntax will look like this each time:

2 SELECT @Sql_Command = '

3 USE [' + @Database_Name + ']';

@Sql_Command is an NVARCHAR(MAX) string that will be used to build, store and execute any
dynamic SQL that we need to use. Any dynamic SQL stored in @Sql_Command that is executed in
the same statement as the dynamic USE will be executed in the context of the database given
by @Database_Name.

We’ll also need to filter our metadata queries based on the schema and table provided in the
parameters. This will require dynamic WHERE clauses that will insert the parameters into those
queries, ensuring we filter effectively. We alternatively could collect metadata on all tables and
schemas and filter later, but this will execute faster and return less extraneous data. A dynamic
WHERE clause searching for a specific schema would look like this:

2 WHERE schemas.name = ''' + @Schema_Name + ''';'

When this WHERE clause is applied to a SELECT query, the results will filter on the schema
provided by the @Schema_Name parameter, allowing us to focus exclusively on the tables that
we care about.

You might also like