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?
1 Answer 1
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);
-
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.Yván Ecarri– Yván Ecarri2021年10月27日 13:59:23 +00:00Commented Oct 27, 2021 at 13:59