Professional Documents
Culture Documents
Tables
Tables
1
3
4'+
9
This first section sets the database context to whatever database we are analyzing and then puts
together the CREATE TABLE statement, filtered on the current table and schema we are working
on. Square brackets are used around all object names, which ensures that we are able to manage
any that have spaces in their names.
Columns
Next, we need to list out the columns in this table, in the correct order, with any relevant
attributes defined inline with the table creation. This is a bit more involved as we may have any
number of columns in a table and any number of attributes in any combination. Our TSQL needs
to be robust enough to deal with any combinations that our schema may throw at us. We’ll break
our workflow down as follows:
1
2 SELECT
12 'CHAR') THEN '(' + CAST(COLUMN_DATA.Column_Length AS NVARCHAR(MAX)) + ')' ELSE '' END + -- Column
13 length (string)
18 Metadata (optional)
19 CASE WHEN COLUMN_DATA.Is_Nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END +
The filter ensures we only add columns for the current table we are working on, while the ORDER
BY puts our data in the correct column order, based on column ordinals. The list-building syntax
used here allows us to build the column list in a single statement from a set of columns of any
size. The final SELECT removes the trailing comma from the string, which is left over by the list-
building syntax.