开发者

Alternate table with new not null Column in existing table in SQL [duplicate]

开发者 https://www.devze.com 2023-01-31 14:36 出处:网络
This question already has answers here: Add non-nullabl开发者_JAVA技巧e columns to an existing table in SQL server?
This question already has answers here: Add non-nullabl开发者_JAVA技巧e columns to an existing table in SQL server? (3 answers) Closed 5 years ago.

How to add not null Column in existing table in SQL Server 2005?


You will either have to specify a DEFAULT, or add the column with NULLs allowed, update all the values, and then change the column to NOT NULL.

ALTER TABLE <YourTable> 
ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>


Choose either:

a) Create not null with some valid default value
b) Create null, fill it, alter to not null


There are two ways to add the NOT NULL Columns to the table :

  1. ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''

  2. ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''


The easiest way to do this is :

ALTER TABLE db.TABLENAME ADD COLUMN [datatype] NOT NULL DEFAULT 'value'

Ex : Adding a column x (bit datatype) to a table ABC with default value 0

ALTER TABLE db.ABC ADD COLUMN x bit NOT NULL DEFAULT 0

PS : I am not a big fan of using the table designer for this. Its so much easier being conventional / old fashioned sometimes. :). Hope this helps answer


IF NOT EXISTS (SELECT 1
FROM syscolumns sc
JOIN sysobjects so
ON sc.id = so.id
WHERE so.Name = 'Table1'
AND sc.Name = 'Col1')
BEGIN
ALTER TABLE Table1
ADD Col1 INT NOT NULL DEFAULT 0;
END
GO
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号