The April Blogger Challenge is from Ed Leighton-Dick and aimed at new bloggers, but anyone is welcome. I’m trying to motivate and cheer people on.
Designating a Primary Key at Design Time
In the first post on this subject, I noted that I often add a primary key after the fact, using ALTER TABLE. However I’ve been wanting to build the habit of adding the PK at design time, inline with the CREATE TABLE statement, so I decided to look up the syntax and start practicing.
The inline code adds a CONSTRAINT clause into the table definition. I can do this in two ways, the most common is after I’ve built all the columns, I add CONSTRAINT, a name (PKUsers) then the PRIMARY KEY keyword with the optional clustered/nonclustered designation, and finally the column(s) in parentheses
Here’s my new code:
The better way, IMHO, is to do this inline if you have one column. I know this isn’t consistent, but I can easily see the constraint this way.
This is more difficult to see if you have multiple columns, but you can do this:
Simple and easy to find the PK now, it’s named correctly, and it’s easy to read.
References
A few places I used
Quick and Easy Blogging
This post occurred to me while I was writing my first post. Actually, this occurred to me first, but I realized that I often do the ALTER method in post 1, so I wrote that first.
Changing to this post required using the same MSDN article, dropping the table, rewriting the DDL code, and testing it. About 5 minutes for this one because it was based on a previous post.
Look for the other posts in the April challenge.
Pingback: SQL New Blogger Digest – Week 2 | The Rest is Just Code
Pingback: Defining Foreign Keys at Table Create Time | Voice of the DBA