📜  sql server alter table columnable - SQL (1)

📅  最后修改于: 2023-12-03 15:05:17.347000             🧑  作者: Mango

SQL Server ALTER TABLE COLUMNABLE

Introduction

In SQL Server, the ALTER TABLE statement is used to modify an existing table, such as adding or deleting columns. The ALTER TABLE COLUMNABLE statement, also known as the ALTER COLUMN statement, is used to alter the properties of a column in a table.

Syntax

The basic syntax of the ALTER TABLE COLUMNABLE statement is as follows:

ALTER TABLE table_name
ALTER COLUMN column_name [new_data_type] [NULL | NOT NULL] [DEFAULT default_value] [IDENTITY [ (seed , increment ) ] ]
Parameters
  • table_name: The name of the table to modify.
  • column_name: The name of the column to modify.
  • new_data_type: The new data type for the column. This parameter is optional.
  • NULL | NOT NULL: Specifies whether the column can contain NULL values or not. This parameter is optional.
  • DEFAULT default_value: Specifies a default value for the column. This parameter is optional.
  • IDENTITY [ (seed , increment ) ]: Specifies that the column is an identity column, and optionally specifies the seed value and increment value. This parameter is optional.
Examples
Example 1: Modify the data type of a column
ALTER TABLE employees
ALTER COLUMN salary DECIMAL(10,2);

This statement modifies the salary column in the employees table, changing its data type to DECIMAL(10,2).

Example 2: Modify the nullability of a column
ALTER TABLE employees
ALTER COLUMN email VARCHAR(255) NOT NULL;

This statement modifies the email column in the employees table, setting its nullability to NOT NULL.

Example 3: Modify the default value of a column
ALTER TABLE employees
ALTER COLUMN hire_date DATE DEFAULT '2022-01-01';

This statement modifies the hire_date column in the employees table, setting its default value to '2022-01-01'.

Example 4: Modify a column to be an identity column
ALTER TABLE orders
ALTER COLUMN order_id INT IDENTITY(1,1);

This statement modifies the order_id column in the orders table, setting it to be an identity column with a starting value of 1 and an increment of 1.

Conclusion

The ALTER TABLE COLUMNABLE statement is a powerful tool for modifying the properties of columns in SQL Server. Proper use of this statement can help to ensure that your database schema remains up-to-date and in line with your application's needs.