Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

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 =

2 @Schema_Name_Current AND PRIMARY_KEY_DATA.Table_Name = @Table_Name_Current AND

PRIMARY_KEY_DATA.Is_Primary_Key = 1)
3

BEGIN
4

SELECT
5

@Schema_Build_Text = @Schema_Build_Text + ',


6

CONSTRAINT ' + PRIMARY_KEY_DATA.Index_Name + ' PRIMARY KEY' + -- Primary key name


7

Index_Type + -- Clustered vs. Nonclustered key.


8

'(' + PRIMARY_KEY_DATA.Index_Column_List + ')' -- Column list.


9

FROM @Indexes PRIMARY_KEY_DATA


10

WHERE PRIMARY_KEY_DATA.Schema_Name = @Schema_Name_Current


11

AND PRIMARY_KEY_DATA.Table_Name = @Table_Name_Current


12

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:


2 SELECT @Schema_Build_Text = @Schema_Build_Text + ');

3 GO';

You might also like