SQL* (1/23/2013)
What is the need of computed column if we can do the same thing in the query/application?
The two big advantages of computed columns are:
1) a consistent definition;
2) defined in only one place.
1) If you define a computed column in the table, you know that all queries are using the same computation to generate the new value. If you specify the computation itself in different queries and views, some of them could be different from each other, possibly even to the extent of making the value incorrect.
2) Say you need to change/update the computation. With a computed column, you simply drop the old definition and add the new one -- all queries automatically now refer to the new definition. If you've done the computation in multiple queries/views, you must find them all and change them -- NOT fun.
For example:
ALTER TABLE dbo.tablename ADD
full_name AS
first_name +
ISNULL(' ' + middle_name, '') +
last_name
--requirement comes in to add a possible "salutation" to full_name
ALTER TABLE dbo.tablename
DROP COLUMN full_name
ALTER TABLE dbo.tablename ADD
full_name AS
ISNULL(salutation + ' ', '') +
first_name +
ISNULL(' ' + middle_name, '') +
last_name
Voila: every use of full_name from then automatically includes the required "salutation" with no other coding changes required.
SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.