Very frequently Jr. Developers request script for creating default constraint over table column. I have written following small script for creating default constraint. I think this will be useful to many other developers who want this script to keep handy.
ALTER TABLE Customers
ADD CONSTRAINT DF_Customers_Address2
DEFAULT 'UNKNOWN' FOR Address2
Reference : Pinal Dave (http://blog.SQLAuthority.com)












i have a problem like this:
i have a column that can get the values: Y or N
how do i wirte a script that allows only one row at every given moment to be Y and all others N.
i want this as a constraint or something like this.
thanks in advance,
Karina
Thank you very much. I´ve just begun to develop things and this script was very useful for me.
2 Karina
use CHECK sample below:
ALTER TABLE
ADD CONSTRAINT CHECK ( IN (‘N’,'Y’));
Hi,
is there a create script that can gather all the existing constraints on all tables in a db?
I have foreign keys, primary keys, indexes and check constraints… but am unable to find one for default constraints.
Thanks
Riccardo
I have a Domain Data table that is being added at the same time a FK is being created refrencing the new table. The problem is the data in the new table is not instered until the post script so the creation of the FK fails. How would you handle this? I tried createing the table in the pre script but then i fail because the table already exists when data dude tries to add it.
hello sir
i read this article and this is correct that we can add the default constraint by this , but on msdn and technet i found different syntax which is not working for me , giving me syntax error
i am also posting the link where i found these information
http://technet.microsoft.com/en-us/library/ms174123.aspx
http://www.w3schools.com/sql/sql_default.asp
http://msdn.microsoft.com/en-us/library/ms174123.aspx
and
the syntax where i getting error is
ALTER TABLE BE_PromoCode
ALTER COLUMN UsePromoNo SET DEFAULT 0
[...] Interview Questions and Answers ISBN: 1466405643 Page#137-139 Prevent Constraint to Allow NULL Create Default Constraint Over Table Column Create Primary Key with Specific Name when Creating Table Creating Primary Key, Foreign Key and [...]
ALTER TABLE [dbo].[table_name] ADD DEFAULT (0) FOR [column_name]
I have done this but now upon insert of a new record the value is not defaulting to 0 (zero) why?