Professional Documents
Culture Documents
Primary Keys
Primary Keys
If the table has a primary key, then we can include that definition defined inline at the end of the
table creation. Since there can only be a single primary key per table, there’s no need to worry
about lists of data. We can generate the script for its creation in a single step as follows:
1
IF EXISTS (SELECT * FROM @Indexes PRIMARY_KEY_DATA WHERE PRIMARY_KEY_DATA.Schema_Name =
PRIMARY_KEY_DATA.Is_Primary_Key = 1)
3
BEGIN
4
SELECT
5
AND PRIMARY_KEY_DATA.Is_Primary_Key = 1;
13
END
14
The IF EXISTS checks if a primary key exists, and if not, this section will be skipped. Otherwise, we
build the primary key creation TSQL using the index information collected earlier, verifying
that Is_Primary_Key = 1. Since we built the index column list earlier, we need only return them
now, without any need for further list building.
Now that we have completed the table creation statement, we can close the parenthesis from
earlier and add a “GO” in order to start a new batch:
1
2 SELECT @Schema_Build_Text = @Schema_Build_Text + ');
3 GO';
4