The ALTER TABLE
statement in Microsoft SQL Server is used to make changes to an existing table structure. This can include adding or deleting columns, changing data types, renaming columns, and more. Here’s a breakdown of how to use ALTER TABLE
for various operations:
Adding a Column
To add a new column to an existing table:
ALTER INDEX index_name ON table_name DISABLE;Example:
Dropping a Column
To remove a column from a table:
Example:
Modifying a Column
To change the data type of an existing column or modify its properties:
Example:
Renaming a Column
To rename an existing column, you need to use sp_rename
:
Example:
Adding a Constraint
To add constraints like primary keys, foreign keys, or unique constraints:
Example (adding a primary key):
Dropping a Constraint
To remove a constraint from a table:
Example (dropping a primary key):
Renaming a Table
To rename a table, you use sp_rename
:
Example:
Modifying Table Options
You can also modify various table options such as enabling/disabling indexes, changing schema, etc. This often involves additional SQL commands or system stored procedures.
Example (disabling an index):
Always make sure to carefully plan and test changes to table structures, especially in production environments, as these operations can have significant impacts on your database and applications.