Adding Computed Columns in SQL Server | SQLYoga

2 0 0
                                        

A scenario that required me to add one calculated column came up today. When a column is computed, it can be used in queries just like any other column and allows us to change one or more columns from the same table.

Lets try it:

Create One Table: tblTestComputed

CREATE TABLE tblTestComputed(
FirstName VARCHAR(50),
LastName VARCHAR(50)
)

Lets insert some data into it:

INSERT INTO tblTestComputed(FirstName, LastName)
SELECT 'Tejas', 'Shah'
UNION
SELECT 'Hiral', 'Shah'

So now I run:

SELECT * FROM tblTestComputed

I will get output like:

Output: www.sqlyoga.com


I now require the display name to be something like "Shah Tejas" or "Shah Hiral". I therefore created a new column and named it:
So, now if I run:

ALTER TABLE tblTestComputed
ADD FullName AS (ISNULL(LastName,'') + ' ' + ISNULL(FirstName,''))

So, now if I run:

SELECT * FROM tblTestComputed

So, Output like:


Output: www.sqlyoga.com


Add a computed column called FullName to your table to combine first and last names, updating automatically.


However, it's essential to note that computed columns cannot be updated directly since they are derived from other columns.


For a deeper dive into computed columns and their applications, Show Our Website (www.sqlyoga.com) to learn more.

You've reached the end of published parts.

⏰ Last updated: May 24, 2024 ⏰

Add this story to your Library to get notified about new parts!

Adding Computed Columns in SQL Server | SQLYogaWhere stories live. Discover now