Published on: 16 Feb, 2021

How to add a new column in TSQL?

Tumblr Digg Google Plus

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.