Professional Documents
Culture Documents
The remainder of the CREATE/ALTER statements can be listed in any order. The order chosen
here was based on which parts of this script were coded first. Feel free to adjust order if it helps
in the consumption of this scripted metadata. In the case of foreign keys, we generated ALTER
TABLE statements previously, which saved time when this moment came along. Here is the
collection TSQL used to initially collect foreign key information:
1
4
5 SELECT
6 FOREIGN_KEY_DATA.name AS Foreign_Key_Name,
7 FOREIGN_KEY_SCHEMA.name AS Foreign_Key_Schema_Name,
8 FOREIGN_KEY_TABLE.name AS Foreign_Key_Table_Name,
WITH '' + CASE WHEN FOREIGN_KEY_DATA.is_not_trusted = 1 THEN ''NOCHECK'' ELSE ''CHECK'' END +
10
21 ON foreign_key_columns.parent_object_id = FOREIGN_KEY_COLUMN.object_id
29 FROM sys.foreign_keys
31 ON foreign_keys.object_id = foreign_key_columns.constraint_object_id
33 ON foreign_keys.referenced_object_id =
REFERENCED_TABLE.object_id
34
ON REFERENCED_KEY_SCHEMA.schema_id =
36
REFERENCED_TABLE.schema_id
37
INNER JOIN sys.columns REFERENECD_COLUMN
38
ON foreign_key_columns.referenced_object_id =
39
REFERENECD_COLUMN.object_id
40
AND foreign_key_columns.referenced_column_id =
41 REFERENECD_COLUMN.column_id
ORDER BY REFERENCED_TABLE.name,
foreign_key_columns.constraint_column_id
GO''
44
AS Foreign_Key_Creation_Script
45
ON FOREIGN_KEY_DATA.parent_object_id = FOREIGN_KEY_TABLE.object_id
48
ON FOREIGN_KEY_DATA.referenced_object_id = REFERENCED_TABLE.object_id
50
ON FOREIGN_KEY_SCHEMA.schema_id = FOREIGN_KEY_TABLE.schema_id
52
ON REFERENCED_KEY_SCHEMA.schema_id = REFERENCED_TABLE.schema_id';
54
List-building via XML was used in order to gather the foreign key column lists, as well as the
referenced column lists all in a single statement. The syntax here is almost identical to that used
for the collection of index key and included column lists. Since this work is already complete, the
steps needed to generate the foreign key creation scripts will be much simpler:
1
Foreign_Key_Table_Name = @Table_Name_Current)
3
BEGIN
4
SELECT
5
@Schema_Build_Text = @Schema_Build_Text + '
6
7
' + Foreign_Key_Creation_Script
8
FROM @Foreign_Keys
9
WHERE Foreign_Key_Schema_Name = @Schema_Name_Current
10
AND Foreign_Key_Table_Name = @Table_Name_Current;
11
END
12
IF EXISTS checks to see if any foreign keys exist on the table, and if so, add the foreign key
creation script onto our schema creation script.