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;


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 ********


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


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


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

Hope this helps