3

I'd like to create a table with a default constraint for a field. I know I can add a constraint after the table is created but I need to create the table and the named default constraint in one single command, like this

create table table1(field1 varchar(25), constraint df_table1_field1 default('a') for field1)

Unfortunately that doesn't work.

Any suggestions?

0
8

Use this syntax:

CREATE TABLE table1
(
    field1 varchar(25) CONSTRAINT [df_table1_field1] DEFAULT('a')
)

Have a look at MS Docs about Specify Default Values for Columns, specifically this secion: Named CONSTRAINT (T-SQL)

CREATE TABLE dbo.doc_exz (
      column_a INT,
      column_b INT CONSTRAINT DF_Doc_Exz_Column_B DEFAULT 50); 
1
  • Awesome! I found out that I can have this also: create table table1(field1 varchar(25) constraint pk primary key constraint df_table1_field1 default('a') ) Thank you. Oct 27 at 13:59

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.