Creating a computed column in SQL Server 2008

Phone Developer picture Phone Developer · Nov 7, 2011 · Viewed 64.8k times · Source

I have a SQL Server 2008 database. This database has a Table called "Book". "Book" has the following properties:

  • ID (int)
  • Title (nvarchar(256))
  • PublishDate (datetime)

I need to create a computed column called "AgeInMinutes". I'm not very familiar with computed columns. I understand the concept, but I'm not sure how to do it. In SQL Server Management studio, in the "Column Properties" area, I see a property called "(Formula)" in the Table Designer section. I assume I need to enter my calculation here. However, I'm not sure what to put here. Can somebody please help me?

Thank you!

Answer

JNK picture JNK · Nov 7, 2011

You can define the column in your CREATE TABLE as:

AgeInMinutes as (DATEDIFF(minute, PublishDate, GETDATE())

Alternatively, just do

ALTER TABLE Book
ADD AgeInMinutes as (DATEDIFF(minute, PublishDate, GETDATE())