If you are into programming you should have definitely worked with calculated fields in SQL. But for others I will briefly explain what they are.
Calculated columns are columns which depend on other columns. It gets its value by calculating which can involve values of other columns. The calculation formula is the only thing stored in the column.
So each time the column is referenced the calculation is done. But if you use the keyword “persisted” while creating the column then the values will be kept in the table. Whenever a referenced value is updated the computed column is also automatically updated to highlight the change. Also by using persisted you can index a computed column.
You can create a table with persisted computed column as follows.
- CREATE TABLE Customer
- (
- CustomerId INT IDENTITY(1, 1) NOT NULL,
- CustomerFirstName NVARCHAR(100) NOT NULL,
- CustomerLastName NVARCHAR(100) NOT NULL,
- CustomerFullName AS CustomerFirstName + ' ' + CustomerLastName PERSISTED
- )
One thing to remember is that you cannot directly insert values to a computed column.
I think you got a basic idea of computed columns. Now I would like to show how to create a computed column dynamically. For example think that you need to add a computed column to a table using a stored procedure. It is not a big deal.
I need to insert a TotalOrder column to the table named FoodOrder.
- CREATE TABLE FoodOrder
- (
- OrderId INT IDENTITY(1, 1) NOT NULL,
- OrderDate SMALLDATETIME NULL,
- CustomerName NVARCHAR(100) NOT NULL,
- TotalStarter INT NULL,
- TotalMainCourse INT NULL,
- TotalSoftBevarage INT NULL,
- TotalLiquer INT NULL,
- TotalDessert INT NULL
- )
This can be done using the following query.
- DECLARE @sExecuteCommand VARCHAR(250), --Keepa the command to be executed.
- @sColumns VARCHAR(150) --Keeps the columns to be included in the formula.
- SET @sColumns = 'TotalStarter+TotalMainCourse+TotalSoftBevarage+TotalLiquer+TotalDessert+'
- SET @sExecuteCommand = 'ALTER TABLE FoodOrder ADD TotalOrder AS ' + SUBSTRING(@sColumns, 1, LEN(@sColumns)-1) -- Creating the computed column.
- EXEC (@sExecuteCommand)
Note that a cursor or a loop can be easily used to populate the variable “sColumns” with the columns required for the formula.
Hope this helps.