|
|
Adding a New Column
|
After a table has already been created, you can still
add a new column to it. In SQL, the basic formula to add a new column to an
existing table is:
ALTER TABLE TableName ADD ColumnName Properties
The ColumnName factor is required. In fact, on
the right side of the ADD keyword, define the column by its name and using
all the options we reviewed for columns.
|
|
- To add a new column to the Contractors table, execute the following
statement:
ALTER TABLE Companies ADD Location varchar(120);
- To add various columns to the Contractors table, execute the following
statement:
ALTER TABLE Contractors ADD PhoneNumber varchar(20), ADD EmailAddress varchar(40), ADD LegalStatus varchar(100);
Renaming a Column
|
If you find out that the name of a column is not
appropriate, you can change it. In MSDE, to change the name of a column, execute sp_rename using the following
formula:
sp_rename 'TableName.ColumnName', 'NewColumnName', 'COLUMN'
The sp_rename factor and the 'COLUMN'
string are required. The TableName factor is the name of the table
that the column belongs to. The ColumnName is the current name of
the column. The NewColumnName is the desired name you want to give
to the column.
Here is an example:
sp_rename 'StaffMembers.FullName', 'EmployeeName', 'COLUMN' GO
When this code is executed, the interpreter will look
for a column named FullName in the StaffMembers table of the current or
selected database. If it finds that column in the table, then it renames
it EmployeeName.
|
Deleting a Column
|
If you have an undesired column that you don't want
anymore in a table, you can remove it. To delete a column, use the following formula:
ALTER TABLE TableName DROP COLUMN ColumnName
On the right side of the ALTER TABLE
expression, type the name of the table. On the right side of the DROP
COLUMN expression, enter the name of the undesired column.
|
|
- To remove a column from the Contractors table, execute the following
statement:
ALTER TABLE Contractors DROP COLUMN MaritalStatus;
- To review the current structure of the Contractors table, execute
the following statement:
DESCRIBE Contractors
- To change the database, execute the following statement:
USE Exercises;
- To delete the EmploymentAgency database, execute the following
statement:
DROP DATABASE EmploymentAgency;
- To end the lesson, type exit and press Enter
No comments:
Post a Comment