Solved

Creating a DB column value by using a formula

Posted on 2008-10-20
3
188 Views
Last Modified: 2010-03-20
Hello Experts,

I have a database table with a Startdate and Endtime column and Total Time Column. I would like to DBMS to automatically calculate my Total Time column. Basically I want to see how long it took a process to finish and have the value in Total Time column. How would I go about achieving this. The Startdate and Enddate columns are datetime.
0
Comment
Question by:rhender9
3 Comments
 
LVL 22

Expert Comment

by:dportas
ID: 22760433
Drop the TotalTime column from your table and put it in a view instead.

CREATE VIEW v1 AS
SELECT StartDate, EndDate,
 DATEDIFF(MINUTE, StartDate, EndDate) TotalTime
FROM tbl ;
0
 
LVL 4

Expert Comment

by:randy_knight
ID: 22760682
you could also do the same thing without a view by making the TotalTime a derived column.  
0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 500 total points
ID: 22761607
I suggest a computed column.  You define this once to SQL and you can reference from then on as if it were a "real" column.  

ALTER TABLE tablename
    ADD TotalTime AS RIGHT(' ' + CAST(DATEDIFF(MINUTE, Startdate, Endtime) / 60 AS VARCHAR(2)), 2) + ':' + RIGHT('0' + CAST(DATEDIFF(MINUTE, Startdate, Endtime) % 60 AS VARCHAR(2)), 2)


Then:

SELECT Startdate, Endtime, TotalTime, ...
FROM ...
WHERE TotalTime >= ' 1:00'  --everything >= 1 hour (for example)
ORDER BY TotalTime
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question