📜  sql server alter column - SQL (1)

📅  最后修改于: 2023-12-03 14:47:35.479000             🧑  作者: Mango

SQL Server ALTER COLUMN

The ALTER COLUMN statement in SQL Server is used to modify the definition of an existing column in a table. It allows you to change the data type, length, nullability, or default value of a column. This can be useful when you need to make changes to the structure of your database without dropping and recreating the table.

Syntax

The basic syntax for altering a column in SQL Server is as follows:

ALTER TABLE table_name
ALTER COLUMN column_name new_data_type;

You can also specify additional settings such as length, nullability, and default value:

ALTER TABLE table_name
ALTER COLUMN column_name new_data_type [length] [NULL | NOT NULL] [DEFAULT default_value];
Examples
  1. Changing the data type of a column:
ALTER TABLE employees
ALTER COLUMN salary DECIMAL(10,2);

This example modifies the salary column in the employees table and changes its data type to DECIMAL(10,2).

  1. Modifying the length of a column:
ALTER TABLE customers
ALTER COLUMN phone_number VARCHAR(15);

In this example, the length of the phone_number column in the customers table is changed to 15 characters.

  1. Setting a column as not null:
ALTER TABLE orders
ALTER COLUMN order_date DATE NOT NULL;

This statement alters the order_date column in the orders table and sets it as NOT NULL, meaning it cannot contain null values.

  1. Adding a default value to a column:
ALTER TABLE products
ALTER COLUMN price DECIMAL(10,2) DEFAULT 0.00;

Here, the price column in the products table is modified to have a default value of 0.00.

Conclusion

The ALTER COLUMN statement in SQL Server allows you to make changes to the definition of an existing column in a table. It provides flexibility in modifying data types, lengths, nullability, and default values. By using this statement, you can easily alter the structure of your database tables without the need for dropping and recreating them.