5

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?

asked Oct 27, 2021 at 13:51
0

1 Answer 1

12

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); 
answered Oct 27, 2021 at 13:54
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. Commented Oct 27, 2021 at 13:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.