Tuesday, August 18, 2009

SQL Alter/ Modify Table

ALTER
/*ALTER TABLE table_name ADD column_name datatype*/
ALTER TABLE tbl1 ADD phone varchar(10);
/*ALTER TABLE table_name DROP COLUMN column_name*/
ALTER TABLE tbl1 DROP COLUMN phone;
ALTER TABLE tbl1 ADD phone varchar(10),mail varchar(4);
ALTER TABLE tbl1 DROP COLUMN phone,mail;
Modify a Table
To modify a table, you use an ALTER TABLE command.You
can use an ALTER TABLE command to add, modify, or drop (remove) columns or constraints.

An ALTER TABLE command has the following syntax
ALTER TABLE table_name predicate
where predicate can be any of the following:
  • ADD COLUMN field type[(size)] [NOT NULL] [CONSTRAINT constraint]
  • ADD CONSTRAINT multifield_constraint
  • ALTER COLUMN field type[(size)]
  • DROP COLUMN field
  • DROP CONSTRAINT constraint

Example
ALTER TABLE table_name MODIFY column_name datatype;

For Example: To modify the column salary in the employee
table, the query would be like

ALTER TABLE employee MODIFY salary number(15,2);//this is error in sql server

(or)

ALTER TABLE employee ALTER COLUMN salary number(15,2);)//this is correct in sql server

No comments:

Post a Comment