ALTER程序用于在已有的数据库表中添加、修改或删除字段、约束或索引。以下是一些常用的ALTER语法示例:
添加列
```sql
ALTER TABLE table_name
ADD COLUMN column_name data_type [AFTER existing_column];
```
例如:
```sql
ALTER TABLE employees
ADD COLUMN email VARCHAR(100) AFTER lastName;
```
删除列
```sql
ALTER TABLE table_name
DROP COLUMN column_name;
```
例如:
```sql
ALTER TABLE employees
DROP COLUMN age;
```
修改列
修改列名:
```sql
ALTER TABLE table_name
CHANGE old_column_name new_column_name data_type;
```
修改列的数据类型:
```sql
ALTER TABLE table_name
MODIFY column_name data_type;
```
修改列的约束(例如,设置为NOT NULL):
```sql
ALTER TABLE table_name
MODIFY column_name data_type NOT NULL;
```
添加主键
```sql
ALTER TABLE table_name
ADD PRIMARY KEY (column_name);
```
例如:
```sql
ALTER TABLE employees
ADD PRIMARY KEY (employeeNumber);
```
添加唯一约束
```sql
ALTER TABLE table_name
ADD UNIQUE (column_name);
```
例如:
```sql
ALTER TABLE employees
ADD UNIQUE (email);
```
添加默认值
```sql
ALTER TABLE table_name
ALTER COLUMN column_name SET DEFAULT default_value;
```
例如:
```sql
ALTER TABLE employees
ALTER COLUMN email SET DEFAULT 'default@example.com';
```
添加检查约束
```sql
ALTER TABLE table_name
ADD CONSTRAINT constraint_name CHECK (condition);
```
例如:
```sql
ALTER TABLE employees
ADD CONSTRAINT chk_age CHECK (age >= 18);
```
添加外键约束
```sql
ALTER TABLE table_name
ADD CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES referenced_table_name (referenced_column_name);
```
例如:
```sql
ALTER TABLE offices
ADD CONSTRAINT fk_officeCode
FOREIGN KEY (officeCode) REFERENCES employees (officeCode);
```
删除约束
```sql
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
```
例如:
```sql
ALTER TABLE employees
DROP PRIMARY KEY;
```
重命名表
```sql
EXEC sp_rename 'old_table_name', 'new_table_name';
```
例如:
```sql
EXEC sp_rename 'employees', 'staff';
```
重命名列
```sql
ALTER TABLE table_name
CHANGE old_column_name new_column_name data_type;
```
例如:
```sql
ALTER TABLE employees
CHANGE lastName firstName VARCHAR(50);
```
这些示例涵盖了ALTER语句的主要用途和语法。根据具体需求选择合适的语法即可。