0

I know I can specify it inline like this:

CREATE TABLE dbo.MyTable
(
    Id INT NOT NULL CONSTRAINT PK_MyTable_Id PRIMARY KEY IDENTITY,
    Created DATETIME NOT NULL CONSTRAINT DF_MyTable_Created DEFAULT GETDATE()
)

But I'd like to put all my constraints at the end of the table definition to keep them separate. I can't seem to find out how to name the column for the default constraint if I put it at the end of the table definition. I can do it with primary/foreign keys and unique constraints, but don't know how to specify the column name with a default constraint.

CREATE TABLE dbo.MyTable
(
    Id INT NOT NULL IDENTITY,
    Created DATETIME NOT NULL,
    CONSTRAINT PK_MyTable_Id PRIMARY KEY( Id ),
    CONSTRAINT DF_MyTable_Created DEFAULT GETDATE()
)

1 Answer 1

2

Do it separate with ALTER TABLE ADD..... syntax

like this

CREATE TABLE dbo.MyTable
(
    Id INT NOT NULL IDENTITY,
    Created DATETIME NOT NULL

)
GO

ALTER TABLE dbo.MyTable ADD CONSTRAINT PK_MyTable_Id PRIMARY KEY( Id ),
CONSTRAINT DF_MyTable_Created DEFAULT GETDATE() FOR Created
GO
Sign up to request clarification or add additional context in comments.

3 Comments

I'd rather do it inline than altering the table.
in that case you would have to do your first option
I take it it's just not possible for a default constraint?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.