Solved

Creating a DB column value by using a formula

Posted on 2008-10-20
3
187 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.‚Äč
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how the fundamental information of how to create a table.

839 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