Sql-server – create table script with constraints in sql server 2008

sql serversql-server-2008

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

Best Answer

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.