?
Solved

Creating a DB column value by using a formula

Posted on 2008-10-20
3
Medium Priority
?
190 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 2000 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

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

Question has a verified solution.

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

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.
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

777 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