I have a SQL Server 2008 database. This database has a Table called "Book". "Book" has the following properties:
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!
We can also create a computed column using the Object explorer window. Go to your database, right click on tables, select “New Table” option. Create all columns that you require and to mark any column as computed, select that column and go to column Properties window and write your formula for computed column.
Use SQL Server Management StudioRight-click Columns and select New Column. Enter the column name and accept the default data type (nchar(10)). The Database Engine determines the data type of the computed column by applying the rules of data type precedence to the expressions specified in the formula.
A computed column in SQL Server is a virtual column that computes its values from an expression. We can use a constant value, function, value derived from other columns, non-computed column name, or their combinations. SQL Server does not store these virtual columns physically, so it does not require any storage.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With