Just a day ago while working with database Jr. Developer asked me question how to add column along with column constraint. He also wanted to specify the name of the constraint. The newly added column should not allow NULL value. He requested my help as he thought he might have to write many lines to achieve what was requested.
It is very easy to add column and specify default constraint. I have seen many examples where constraint name is not specified, if constraint name is not specified SQL Server will generate unique name for itself. I prefer to specify my constraint name as per my coding standards. You can read my coding standard here : SQL SERVER Database Coding Standards and Guidelines Complete List Download
ALTER TABLE TestTable
ADD NewCol VARCHAR(50)
CONSTRAINT DF_TestTable_NewCol DEFAULT '' NOT NULL
GO
Reference : Pinal Dave (http://blog.SQLAuthority.com)




Dave,
I think something is wrong with your blog software. The new blog post today is labeled as the 19th, but you posted it today, 3/21. Just wanted you to be aware.
hello sir,
i could not delete a column in a table through ‘ drop column’ option in ‘alter table’ query even though the column is not having any relationships or any other constraints.
please help me.
with regards,
adiraju
@adiraju
If that column you are trying to drop is used by any derived column, then you cannot drop it.
Example: in Example11 I created a table with out any derived column so I was able to drop column ename.
CREATE TABLE EXAMPLE11( EID INT , ENAME VARCHAR(10))
GO
ALTER TABLE EXAMPLE11
DROP COLUMN ENAME
GO
Result:Command(s) completed successfully.
Example2: In this example I created third column using first and second column, so when I try to drop second column, it gives me an error because second column in used in third column
CREATE TABLE EXAMPLE12 ( COLA INT, COLB INT , COLC AS COLA + COLB )
GO
ALTER TABLE EXAMPLE12
DROP COLUMN COLB
Go
Result: Msg 5074, Level 16, State 1, Line 1
The column ‘colc’ is dependent on column ‘COLB’.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE DROP COLUMN COLB failed because one or more objects access this column.
Hope this helps.
Thanks,
Imran.
Hi,
Can someone please tell me how to specify a default constraint for an existing column?
Thanks in advance!!
Treasa
Dear Treasa!
ALTER TABLE TableName WITH NOCHECK
ADD CONSTRAINT DF_DefaultName DEFAULT ‘Default Value’ FOR ColumnName
Check it out !
I have an existing query which return 1000 of rows, i want to add another column and have constant numerical value (2.7 for example). can someone tell me how to do that? many thanks
até que enfim um exemplo simples e eficaz. boa=good!
Thanks for the solution. Works!