Computed Columns in SQL Server


Tables can have computed columns. It is an expression defining the value of the specified column. If you are creating a table object in Query Window the columns don't have data by default. But using the Computed Columns method you can fill data as you like.

Lets make an example for it.
Assuming you have a database named SampleDatabase, write a query:

Use SampleDatabase;

GO

Create Table ComputedColumns

(

Quantity int NULL,

Cost money NULL,

Investment as (Quantity * Cost)

);


We're creating a table named ComputedColumns and setting 3 columns "Quantity", "Cost" and "Investment"

Because of the multiply of Quantity and Cost will lead us to Investment costs, it would be useful if we define Investment as variable storing the data of multiplication of these 2 variables.

Because if there's no variable defined for Investment, you won't be able to insert any datas manually. Its data will be calculated and recorded after you passed it.

Lets see the results:
********
Added "2" in the Quantity Column ********


1.png

******** Added "1.000" in the Cost Column *******

2.png

******** You cant add any data into Investment column, so you passed ******

3.png

After this process, it automatically calculates the data as you can see.


Hope this helps

Up Next
    Ebook Download
    View all
    Learn
    View all
    Araf Global is a software consultancy company founded in 2016 focusing on cutting edge technologies.