Computed column
Today when I was looking into the new features of SQL server 2005, I came across a concept of computed columns and thought of sharing with you all. Usually we use computed columns of dataset in application side with adds overhead to the application and potentially reducing the performance of the application. Computed columns in the dataset in the application side can be replaced with computed columns in the SQL server table.
A computed column is not a physical column in a table but computed from an expression that uses other columns in the same table. The data’s in the computed columns will not be saved physically in the table unless it is marked as PERSISTED. When a computed column is marked as persisted index can be created on it. For example computed columns could have the definition datediff(year,[DOB],getdate()). The expression can be a non-computed column name, constant, function, variable and any combination of their connected by one or more operators. The expression cannot be a sub query or include an alias data types. A computed column cannot be used in INSERT and UPDATE statement. A computed column can be used as a foreign key only if it is marked as PERSISTED. Enforcing check constraint, null or not null on the computed column also requires the column to be marked PERSISTED.
Example of using computed column:
CREATE TABLE [dbo].[TableFeatures](
[ID] [int] NULL,
[Name] [varchar](100) NULL,
[DOB] [datetime] NULL,
[AGE] AS (datediff(year,[DOB],getdate()))
) ON [PRIMARY]
Example of insert statement:
INSERT INTO Tablefeatures VALUES(1,'sathya','1983-11-02')
INSERT INTO tablefeatures VALUES(2,'sathya','1981-11-02')
INSERT INTO tablefeatures VALUES(3,'sathya','1982-11-02')
Output of the select statement:
ID Name DOB Age
1 sathya 1983-11-02 00:00:00.000 25
2 sathya 1981-11-02 00:00:00.000 27
3 sathya 1982-11-02 00:00:00.000 26
Comments