Wednesday, 15 August 2007

General alter table syntax

To add a primary key:
ALTER TABLE TableName ADD CONSTRAINT ConstraintName PRIMARY KEY (ColumnName)

For composite key, simply specify mutiple columns:
ALTER TABLE TableName ADD CONSTRAINT ConstraintName PRIMARY KEY (ColumnName1, ColumnName2)

To add a foreign key:
ALTER TABLE ChildTableName ADD CONSTRAINT FK_NAME FOREIGN KEY (ChildTableColumnName) REFERENCES ParentTable(ParentTableColumnName)

To add a unique key:
ALTER TABLE TableName ADD CONSTRAINT UNIQUE_NAME UNIQUE (ColumnName)

To add a column:

ALTER TABLE TableName ADD ColumnName int NULL

ALTER TABLE TableName ADD ColumnName int NOT NULL DEFAULT(0)


Note thate when you are adding a NOT NULL column which does not have a default value the statement would fail. If it has to be a NOT NULL column, you should add it as a NULL column first, update the table and set values of that column, then change it to NOT NULL with alter table statement. For example,

ALTER TABLE TableName ADD ColumnName int NULL

UPDATE TableName SET ColumnName = ColumnName2 + 1

ALTER TABLE TableName ALTER COLUMN ColumnName int NOT NULL

No comments:

Post a Comment