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]
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.
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);
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With