Tuesday, May 17, 2011

Alter Table Add Column

Adding a column to a table in SQL Server is done using the ALTER TABLE tablename ADD command. When adding columns you can specify all the same settings available when creating a table.

In the example below, we will create a small sample table, then add columns using the ALTER TABLE command.

Multiple columns can be specificied by using the syntax below. First issue an alter table command then add the column name, data type, nullable, and default value.

CREATE TABLE dbo.Employees
(
EmployeeID int IDENTITY (1,1) NOT NULL PRIMARY KEY NONCLUSTERED
)
GO
ALTER TABLE dbo.Employees
ADD
FirstName varchar(50) NULL
,LastName varchar(50) NULL
,SSN varchar(9) NULL CONSTRAINT ssn_unique UNIQUE
,IsTerminated bit NOT NULL DEFAULT 0
,DateAdded datetime DEFAULT GETDATE()
,Comments varchar(255) SPARSE NULL -- SQL Server 2008 sparse column

0 Comments:

Post a Comment