I have create table scripts and alter table scripts with some constraints for that database.

It take time as twice to create the table and alter the table .. Is this possible to combine

create table and alter table constraints with create table script..in sql server 2008

  • Please show your create and alter scripts. – Martin Smith Jan 21 '12 at 10:14

Here's an example of creating a constraint at the same time as a table:

create table Table1
multiplier1 int,
multiplier2 int,
answer int,
constraint PK_Table1 primary key(multiplier1, multiplier2),
constraint CHK_Table1_Answer check (answer = multiplier1 * multiplier2),
check (answer / multiplier1 = multiplier2)

Per @Martin Smith's comment, the constraint name is optional. The database will generate a name for the third constraint, like CK__Table1__22AA2996.

Constraints that are introduced on their own line can can refer to multiple columns.

  • 2
    They don't have to be named. The [constraint constraint_name] bit is optional. – Martin Smith Jan 21 '12 at 12:04
  • 1
    Also, whether column level or table level, the constraint name is always optional – gbn Jan 21 '12 at 12:07
  • 1
    @MartinSmith: Interesting, info added to the question – Andomar Jan 21 '12 at 12:08
  • 1
    Just want to interject that it's usually a best practice to name your constraints. It's much easier of course to use the simpler syntax and leave them out, but if you need to build change scripts it is much easier to rely on a standard naming scheme than having to determine the system-generated name from the metadata. The standard you use doesn't matter, as long as it's consistent and documented. – Aaron Bertrand Jan 21 '12 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.