Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add DEFAULT constraint with a generated name

In SQL Server I have an existing table. Now I want to add a DEFAULT constraint to one of the columns - without having to define a name for it.

-- generated name works fine when creating new column
ALTER TABLE [xyz]
ADD [newColumn] int NOT NULL DEFAULT 0

-- when adding a default value afterwards I seem to have to provide a name
ALTER TABLE [xyz]
ADD CONSTRAINT [iDontWantToPutANameHere] DEFAULT 0 FOR [existingColumn]
like image 802
slartidan Avatar asked Jan 29 '16 14:01

slartidan


People also ask

How do you name a default constraint?

To maintain compatibility with earlier versions of SQL Server, a constraint name can be assigned to a DEFAULT . so if you want to add a default constraint (naming or not) the only ways are by doing it inline or with an ALTER TABLE statement.

How do you add a constraint to a name?

For example, to add a unique constraint to the fname and lname columns of the customer table, use the following statement: ALTER TABLE customer ADD CONSTRAINT UNIQUE (lname, fname);


2 Answers

You can create default constraint for an existing column, without specifying its name, e.g.:

create table test
(
    existing_column int
)

alter table test
    add default 0 for existing_column

However, there are plenty articles, suggesting that it is better to name constraints explicitly. Because of it is harder to drop or other way alter system-named constraint. Also if you have multiple instances of the same database, the default name will no be the same across them.

like image 158
i-one Avatar answered Nov 12 '22 01:11

i-one


Pretty sure the only way you can add a default constraint to an existing column is by naming it.

If it's THAT important to you to get a system-generated name, you can do this:

  1. Alter Table adding new column with un-named DEFAULT value.
  2. Update Table, setting the values of the new column to the values of the old column.
  3. Drop the old column.
  4. Rename the new column to the name of the old column.

Personally I wish that SQL Server didn't give any option for not naming your constraints. I hate dealing with the system generated names that some lazy developer left behind.

like image 34
Tab Alleman Avatar answered Nov 12 '22 01:11

Tab Alleman