May 24, 2021 07:09 by
Peter
In this article, we will see what ‘Computed Column in SQL Server' is, and how we can use it.
First of all, what is a Computed column in SQL Server?
Computed column as the name gives an idea it's related to something calculation/ computation, yes, computed columns are similar to a column in Excel with an applied formula that calculates the value automatically of the given query or the columns.
Computed columns are columns with some user-defined expression or with some formula to calculate the corresponding columns with operators or with some query.
Let's take an example,
Creating a table named 'CalculationTable' with a computed column named 'Age',
Create table CalculationTable
(
ID INT IDENTITY(1,1) PRIMARY KEY,
NAME NVARCHAR(50) null,
DATEOFBIRTH DATE null,
AGE AS (DATEDIFF(YEAR,DATEOFBIRTH,GETDATE()))
)
You can also use the SSMS user interface to define that column (formula), let’s see how,
Now let's insert some data into the table,
In the above example, AGE is computed column, whenever we insert the value of DATEOFBIRTH then AGE will be calculated automatically.
I hope this will be helpful to understand the Computed Columns in SQL Server.
For practice, you can download the attached scripts.
HostForLIFEASP.NET SQL Server 2019 Hosting