Need output by combining DATEDIFF(hh,StartTime,EndTime) + 'Minutes' in SQL Server - sql

When running this query, I need output by combining
DATEDIFF(mm, StartTime, EndTime) + 'Minutes'
I'm getting this error
Conversion failed when converting the varchar value 'Minutes' to data type int
I need to achieve the output like 15 Minutes.
(15 represents the difference between StartTime and EndTime)

DATEDIFF function returns a INT values.
So you need to CAST it to a string.
Try something like
SELECT CAST(DATEDIFF(mm,StartTime, EndTime) AS NVARCHAR(2)) + 'Minutes'
Obviously you can use other destination string type like char\nchar etc... And use the CONVERT function instead of CAST.

Use CONCAT():
select concat(DATEDIFF(minute, StartTime, EndTime), 'Minutes')
CONCAT() will conveniently convert arguments to strings. Also note that this spells out minute. I recommend using the full name when using date functions.

Related

SQL Creating a table for song duration

I am trying to create a table in SQL which is about Music, it should contain songDuration. Which means I gotta hold minutes:seconds information in the table. But i have no idea what to use for the type. I am using SQL server.
Edit: I want to use the database for an ASP.NET Core web application. I was using a ready-to-use SQL database like northwnd. Now, I am trying to create one. So, I will not see the timing with SELECT function in SQL query. So, I need to use something that makes it mm:ss otomaticly. Is there is a type that I can decleare like that?
create table musics(
songDuration type,
...)
Why just don't you use int?
So you could calculate duration in the way you like.
E.g. minutes,hours, etc.
There's a datatype time which would be the logical choice, that stores it in format HH:mm:ss with an optional amount of fractional seconds determined by the size you declare the field (e.g. time(3) holds it to three decimal places)
If your source data is already in this notation it makes it getting it in the table easy and simple sorting/filtering operates as you expect. The downside to doing this is if you want to do certain operations such as SUM or AVG (because as a_horse_with_no_name pointed out in their comment) time technically represents a point in time not a duration and you'd have to do some workaround like so:
SELECT totalduration = SUM(DATEDIFF(SECOND, '0:00:00', duration))
FROM dbo.table
Alternatively you could store the number of (say) seconds in the duration using an int, but if you don't already have the information in that format you'd have to do some (light) conversion when inserting the data, and then back if you want to display in mm:ss
e.g:
SELECT CONVERT(varchar, DATEADD(SECOND, durationinseconds, 0), 8) FROM dbo.table
which would convert it back to hh:mm:ss format.
I do this by using an int column, and store the seconds there.
In your client you can calculate from the seconds howmany days, hours, minutes and seconds it is and display it like you want.
To display it in sql you can use this for example
declare #seconds int = 350
select right('00' + convert(varchar, datepart(hour, dateadd(s, #seconds, 0)) + ((#seconds / 86400) * 24)), 2)
+ ':' + right('00' + convert(varchar, datepart(minute, dateadd(s, #seconds, 0))), 2)
+ ':' + right('00' + convert(varchar, datepart(second, dateadd(s, #seconds, 0))), 2)
this will display
00:05:50
which is 0 hours, 5 minutes and 50 seconds
IF the value of seconds is larger than a day, this will be no problem. The number of hours will simply be greater
a value of 350000 will display 97:13:20

SQL Server: convert and merge separate date and time columns (both integers)

I am working on a query, where I have to fill a table's column ([Result_DateTime]) with datetime values.
The datetime based on two columns, both integer. One contains the date and the other is the time, as it is.
As you can see from the picture, it is a bit difficult to merge and convert these values to an actual datetime, because of the way they are stored. Mainly the time value causing problems.
I concluded how to convert the date column:
CONVERT(DATETIME, LEFT(20200131, 8))
but then I got stuck - what to do with the time and how to merge the two into one datetime effectively?
Using function STUFF looks nasty...
Could you help me out please? I am using SQL Server 2014
Below is one method to do it:
SELECT CAST(Convert(DATE, LEFT(DATEUPDT, 8)) AS VARCHAR(10)) +' '+CAST (TIMEUPDT/100 AS VARCHAR(4)) + ':' + CAST(TIMEUPDT%(100 * (TIMEUPDT/100)) AS VARCHAR(10))+':00'
FROM TEST_TABLE_TIME;
I think I found one solution. What I tried is to avoid using varchar conversions because of how the time column's zeros are cut off. However, I am not convinced that this is the most effective way to do so:
DECLARE #DateInt int = 20200131
DECLARE #TimeInt int = 345 -- 03:45:00
SELECT CONVERT(DATETIME, LEFT(#DateInt, 8)) +
CAST(DATEADD(second, FLOOR(#TimeInt / 100) * 3600 + FLOOR(#TimeInt / 1) % 100 * 60, 0) as datetime)
I was testing it with various time values, it is working.

Calculate Time Difference for Date/Time Variable

I have two variables 'triage_date_time' and 'checkin_date_time'. Both are formatted as, for example, 2018-12-31 14:13:00. Showing the year-month-day and hour-minute-second both within one cell.
I wanted to create a variable that calculates the time it takes from check-in to triage.
I attempted to use the following code:
SELECT DISTINCT datediff(minute, 'triage_date_time', 'checkin_date_time') as
checkin_to_triage
However, when running this code I get the following error... "Conversion failed when converting date and/or time from character string".
Any suggestions of how I can write a code that would calculate the minute difference of these two variables.
Thanks!
One problem is obviously the single quotes. Assuming that you are using SQL Server, variables start with #. So:
select datediff(minute, #triage_date_time, #checkin_date_time) as checkin_to_triage
If you are confused and really mean columns in a table, then:
select datediff(minute, triage_date_time, checkin_date_time) as checkin_to_triage
from t;
could it be that your field is a CHARACTER data type ?
cast your char to datetime
SELECT DISTINCT datediff(minute, CAST(triage_date_time AS datetime), CAST(checkin_date_time AS datetime)) as checkin_to_triage
Try with this query
DECLARE #triage_date_time DATETIME = '20181231 14:13:00'
DECLARE #checkin_date_time DATETIME = '20181231 16:13:00'
SELECT DATEDIFF (MINUTE, #triage_date_time, #checkin_date_time) AS 'checkin_to_triage'
Output :
checkin_to_triage
120

Msg 242: conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I have gone through a bunch of posts here with this error and tried changing data types and used Convert but nothing seems to fix this. So I would like to ask for some help here. I will try to give as much info, but feel free to ask if its not enough.
This is where I am getting the error:
Insert into prompt(ID, Date)
select
ROW_NUMBER() over (order by b.IDLoc),
[dbo].[fn_GetGPtime](cast (replace(DateCollected, '/', '-') + ' ' + a.UTCTime as datetime))
from
Img a
inner join
Tloc b on a.Filename = b.filename
order by
b.IDLoc
The Date column in prompt table has a datatype of float. UTCTime and DateCollected are both varchar(20)
The error is:
Msg 242, Level 16, State 3, Line 274
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Here is the function:
[dbo].[fn_GetGPtime] (#UTCtime datetime)
returns varchar(50)
AS
BEGIN
return (DATEPART (WEEKDAY, #UTCtime) - 1) * 86400 ---day
+ DATEPART (HOUR, #UTCtime) * 3600 ---hour
+ DATEPART (MINUTE, #UTCtime) * 60 ----minutes
+ DATEPART (SECOND, #UTCtime) ---second
+ (DATEPART (MILLISECOND, #UTCtime)) * 0.001 ---ms
+ (DATEPART (MICROSECOND, #UTCtime)) * 0.000001 ---us
+ 16 ----leap seconds
end;
To get an idea of the data itself:
How do I fix this issue?
Your error message could mean two different things: that you have non-convertible data in some cells, or that field's data are not convertible to datetime at all.
You can use try_convert instead of convert to figure out which it is. It will solve your problem if you have a few completely unusable values (i.e. bad data); you'll get nulls for bad data and good conversion for good data. If the overall conversion is never going to work you'll get all nulls and you'll know it isn't just a few bad values.
Another thing you could try is converting from float to numeric before converting to datetime. I find that float formatted data are awful for conversions and converting to numeric can remove many issues. You'd have something like convert(datetime, convert(numeric(18,2), UTCTime))
Use convert instead of cast. When using convert, you can specify the format of the string representing the date.
Once you've converted DateCollected to datetime, you can cast a.UTCTime to datetime and add them together:
Insert into prompt(ID,Date)
select ROW_NUMBER() over (order by b.IDLoc),
[dbo].[fn_GetGPtime](convert(datetime, DateCollected, 101) + cast(a.UTCTime as datetime))
from Img a inner join Tloc b on a.Filename=b.filename
order by b.IDLoc
(assuming a.UTCTime is either varchar or time)
What worked for me, solving this error on an input line such as
SELECT CAST(N'2003-12-01 14:20:47.000' AS DateTime) AS result
Msg 242 Level 16 ...
is the magic instruction:
SET DATEFORMAT ymd;

String manipulation on a converted datetime to varchar t-sql

I have a smalldatetime field I am converting to varchar (which works fine) now I wanna cut it in the select query to only return the time and not the date.
convert(varchar, [DTMON_F]) as mondayFrom
This returns "Feb 28 2011 10:30AM" I want to just return "10:30AM"
You could use one of the predefined format styles that only contain time parts, such as:
convert(varchar, [DTMON_F], 108)
convert(varchar, [DTMON_F], 114)
if they give you a suitable output.
Otherwise you can create your own output by concatenating results of various DATEPART function calls.
Try RIGHT(CONVERT(VARCHAR, [DTMON_F]), 7)
http://msdn.microsoft.com/en-us/library/ms187928%28v=SQL.105%29.aspx
Two ways spring to mind
select convert(varchar,[DTMON_F],8) as mondayFrom
will return 10:30:00 (in 24hr format)
select ltrim(right(convert(varchar,[DTMON_F]),7)) as mondayFrom
will return 10:30PM