Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Friday, 16 February 2024

Changing a column Datatype length in MSSQL

In Microsoft SQL Server (MSSQL), you can change the length of a column datatype using the ALTER TABLE statement combined with the ALTER COLUMN clause. Below are examples demonstrating how to change the length of columns for various datatypes:

1. Changing VARCHAR/NVARCHAR length:

Suppose you have a table named MyTable with a column named MyVarcharColumn of datatype VARCHAR(50), and you want to change its length to VARCHAR(100).

ALTER TABLE MyTable

ALTER COLUMN MyVarcharColumn VARCHAR(100);

2. Changing CHAR/NCHAR length:

Suppose you have a table named MyTable with a column named MyCharColumn of datatype CHAR(10), and you want to change its length to CHAR(20).

ALTER TABLE MyTable

ALTER COLUMN MyCharColumn CHAR(20);

3. Changing NVARCHAR length:

Suppose you have a table named MyTable with a column named MyNvarcharColumn of datatype NVARCHAR(50), and you want to change its length to NVARCHAR(100).

ALTER TABLE MyTable

ALTER COLUMN MyNvarcharColumn NVARCHAR(100);

4. Changing VARCHAR(MAX)/NVARCHAR(MAX) length:

Suppose you have a table named MyTable with a column named MyMaxColumn of datatype VARCHAR(MAX), and you want to change its length to VARCHAR(5000).

ALTER TABLE MyTable

ALTER COLUMN MyMaxColumn VARCHAR(5000);

5. Changing numeric types precision/scale:

Suppose you have a table named MyTable with a column named MyDecimalColumn of datatype DECIMAL(10,2), and you want to change its precision to DECIMAL(12,2).

ALTER TABLE MyTable

ALTER COLUMN MyDecimalColumn DECIMAL(12,2);

6. Changing datetime types:

Suppose you have a table named MyTable with a column named MyDatetimeColumn of datatype DATETIME, and you want to change its datatype to DATETIME2(3).

ALTER TABLE MyTable

ALTER COLUMN MyDatetimeColumn DATETIME2(3);

These examples demonstrate how to change the length or precision of columns for various datatypes using the ALTER TABLE statement in MSSQL. Make sure to review and handle any potential data loss or truncation issues before altering the column datatype length or precision.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.