IMG-LOGO

How to add a new column in TSQL?

andy - 16 Feb, 2021 2010 Views 0 Comment

If you need to add a new column in TSQL. You need to use the keyword function 'ALTER TABLE'. It is recommended you perform a check if the proposed column you want to add is not already existed in the database table otherwise you will receive an error message.

Let says we have a table called products with the following columns of information.

If we want to add a column named 'Description' with column type NVARCHAR(MAX) and we want to set the default value for a new column with an empty string and do not allow NULL value.

Here is the full TSQL query to add a new column in SQL Server.


IF NOT EXISTS(SELECT 1 FROM sys.columns
          WHERE Name = N'Description'
          AND Object_ID = Object_ID(N'dbo.Products'))
BEGIN
    ALTER TABLE dbo.Products
    ADD Description NVARCHAR(MAX) DEFAULT '' NOT NULL
END

GO

Here is the final design of the table after we add the new column.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to restore database using SQL query in TSQL?

If you have a database backup bak file extension and want to restore it using SQL query You can use the built in RESTORE DATABASE function Remember in order to be able to restore a database successfully You need to ...

How to get all table sizes in TSQL?

To get the information about how much space or size used by tables You can retrieve the size information by linking multiple tables in sys tables There are two tables that hold this information The first one is the sys ...