Search code examples
sqlsql-server-2008clustered-index

Creating a table with a compound primary key


Ok I want to create a table

TABLE log_table
email nvarchar(255)
,salesrep nvarchar(20)
,blastid int
,timestamp datetime

Now the default value for the timestamp would be the datetime of when the record is inserted and I want the primary key to be on email and blastid.

I know you can do it with clustered indexes but I am not sure on the syntax on how to make that happen. Please, any help would be greatly appreciated. I am using SQL Server Management Studio 2008


Solution

  • CREATE TABLE dbo.log_table
    (
        email nvarchar(255) NOT NULL,
        salesrep nvarchar(2) NULL,
        blastid int NOT NULL,
        timestamp datetime NULL
    )
    
    ALTER TABLE dbo.log_table ADD CONSTRAINT
    DF_log_table_timestamp DEFAULT GetDate() FOR timestamp
    
    ALTER TABLE dbo.log_table ADD CONSTRAINT
    PK_log_table PRIMARY KEY CLUSTERED 
    (
        email,
        blastid
    )
    GO
    

    If you are using the create table GUI, you can use control while clicking columns to set as primary keys.