Monday, March 25, 2013

Computed Column in SQL Table


Computed Column:

We can add computed column in SQL Database tables where the value of one column is calculated from one or more columns of the same table. While creating table we have to use the column name for calculation of computed column.

Example:

I want to calculate the Square, Cube etc of the Number and store in database. For this i have the following create table statement

CREATE TABLE ROOTS
(
Num Int,
Sq As (Num * Num),
cub As (Num * Num * Num)
)

Here first column of the table definition is number for which I want to calculate the Square and Cube, so while adding second column as Sq (Square) I have used first column name Num * Num, and same way for cube.

Insert values in table.

Insert one value at a time into table.
INSERT INTO ROOTS VALUES (-1)

Insert more than one value into table.
INSERT INTO ROOTS VALUES (1) , (2) , (3) , (4) , (5) , (6) , (7) , (8)


One computed column we can not use for the calculation of another Computed column. If we try to create table definition as shown below

CREATE TABLE ROOTS
(
Num Int,
Sq As (Num * Num),
cub As (Sq * Num)
)

SQL Query Analyser will throw the following error

"Msg 1759
Computed column 'Sq' in table 'Roots' is not allowed to be used in another computed-column definition."

No comments: