I am trying to write a query for round up a time functionality as same as MRound
(Ex: =MRound(2015-1-1 10:10:000,"1:15")) function in Excel.
I would like to roundup the given time to 75 minutes [1 Hr and 15 Min].
i am trying to write a query for the same but my excel out put [for given input] is not matching with sql query output.[expecting output same as excel]
Currently i am using below code to roundup but output is not matching with Excel Mround function output.
DECLARE #RoundedTime smalldatetime
DECLARE #Multiplier float
DECLARE #Time datetime
DECLARE #RoundTo float
set #Time='1900-1-1 00:00:00'
set #RoundTo=1.25
SET #Multiplier= 24.00/#RoundTo
SET #RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,#Time,121) AS datetime) AS float) * #Multiplier,0)/#Multiplier
select #RoundedTime
Ex -In Excel if i want to round up "01-01-1900 12:00:00 AM" date then it will give "00-01-1900 23:45" as output but in sql it will give "1900-01-01 00:00:00"
could you please help me to resolve this issue.
DECLARE #Time datetime
DECLARE #RoundTo float
set #Time='1900-1-1 00:00:00'
set #RoundTo=1.25
SELECT CAST(#Time AS DATETIME) +
CONVERT(DATETIME, DATEADD(MINUTE, 60 * #RoundTo, 0));
RESULT: 1900-01-01 01:15:00.000
Related
I tried to convert a varchar variable stored in my database as HH:MM:SS to an actual datetime format HH:MM:SS. I did get the value for HH:MM:SS but the attempt also prefixed the YYYY:MM:DD along with the expected result.
Following is the code that I used to convert this varchar value to HH:MM:SS and the result I got.
Code I tried :
DECLARE #Duration Varchar(10)
SET #Duration = '00:01:23'
SELECT CONVERT(datetime, Duration, 8) AS duration
The output I got :
1900-01-01 00:01:23.000
The expected output:
00:01:23
Please let me know what needs to be changed in this. Thank you!
If you want time, why are you converting to datetime? Given the name it shouldn't be surprising you get both date and time. Try:
DECLARE #Duration char(8) = '00:01:23';
SELECT duration = CONVERT(time(0), #Duration);
Results:
duration
00:01:23
Example db<>fiddle
Just keep in mind that time (nor any date/time type) is not meant to represent a duration or interval. Because what happens when your duration or interval exceeds 24 hours?
What you posted is a time, not a date or datetime. A duration isn't a date. The date types are binary, they don't have prefixes.
You can define a time directly with :
Declare #Duration time ='00:01:23'
Or you can cast a string to a time:
Declare #Duration varchar(10)
Set #Duration = '00:01:23'
Select cast(#Duration as time) as duration
or
Declare #Duration varchar(10)
Set #Duration = '00:01:23'
Select convert(time, #Duration,8) as duration
Unfortunately that's not a duration, it's a time of day. It can only store values between 00:00 and 23:59:59.9999999.
SQL Server has no interval/duration type.
Declare #Duration Varchar(10)
Set #Duration = '00:01:23'
select convert(time,#duration,8);
I am working on migrating an Access program into SQL Server.
The following is my SQL code taken directly from access.
(([Promise Date])-([Date Recieved]))/100
As you can see, I am attempting to do a division on a datetime value.
This is the error message i receive:
Msg 257, Level 16, State 3, Line 1
Implicit conversion from data type datetime to int is not allowed. Use the
CONVERT function to run this query.
Both fields are type Datetime. Any ideas what I am missing?
I think if I am right you are looking for something like this
SELECT DATEDIFF(day, [Promise Date], [Date Recieved])/100;
If right you can get more details here
since dates in access are effectively stored as DOUBLE, I would recommend converting to the SQL float type to handle any part days
(cast([Promise Date] as float) - cast([Date Recieved] as float))/100
check out the following example, the different ideas here give quite different answers
declare #x as datetime = '19960420 15:05:48';
declare #y as datetime = '19960423 18:09:23';
select (CAST(#y as float) - CAST(#x as float)) / 100
select (CAST(#y as int) - CAST(#x as int)) / 100
select datediff(day,#x,#y) / 100
select cast(datediff(day,#x,#y) as float) / 100
Access should treat the dates as floats, with the fractional part representing time, and the integer part representing days
Declare #pd Date = '2019-01-15'
Declare #dr Date = '2019-01-12'
Select Cast(DATEDIFF(d,#dr,#pd) As Float) /100
Result
0.03
UPDATE: As per Cato's comment to allow for DateTime
Declare #pd DateTime = '2001-01-01 19:00:00'
Declare #dr DateTime = '2001-01-05 13:00:00'
Select (Cast(DATEDIFF(hh,#dr,#pd) As Float)/24) / 100
Result:
-0.0375
I need to get a random date-time within a range of 2 date-times in T-SQL for MS-SQL server 2012. It is necessary for me that it goes to the precision of seconds, I need DATETIME2(0) as datatype for both input and output. I have done some research online but the answers I could find are either for dates only or are for other database types.
The code should do something like:
Input: ('2015-01-01 08:22:13' , '2015-03-05 17:56:31') <-- I will use a select statement to replace these absolute numbers
Return: ('2015-02-11 14:32:45') <--this should be randomized
Can anyone help me out with this?
Thanks in advance
One option is to randomize the numbers of seconds between FromDate and ToDate, and then add it to FromDate. Hope it works for you.
DECLARE #FromDate DATETIME2(0)
DECLARE #ToDate DATETIME2(0)
SET #FromDate = '2015-01-01 08:22:13'
SET #ToDate = '2015-03-05 17:56:31'
DECLARE #Seconds INT = DATEDIFF(SECOND, #FromDate, #ToDate)
DECLARE #Random INT = ROUND(((#Seconds-1) * RAND()), 0)
SELECT DATEADD(SECOND, #Random, #FromDate)
I am working with stored procedure while coding I feel some difficulties to add an hour to a time.I mean I have already a predefined time like 08:00 in my database and now I want to add 4 to this time and I want to get result as 12:00. How can I achieve it?? The way which I tried is below,
ALTER PROCEDURE [dbo].[AttandenceEdit1](
#machid numeric(18,0),
)
AS
declare #time as time(0),#castedtime as time(0),
set #timein1=(select convert(time(0), from ShiftType where machId=#machid )// Value=08:00
print #time
set #addvalue =(DATEADD(HH,#timein1,4))
print #addvalue
I want the result 08:00+4=12:00
now it show error like Argument data type time is invalid for argument 2 of dateadd function
You have the arguments to dateadd in the wrong order. This:
declare #time as time(0)
set #time='08:00'
print #time
declare #addvalue time(0)
set #addvalue =(DATEADD(HOUR, 4, #time))
print #addvalue
Will result in:
08:00:00
12:00:00
There are other issues with your stored proc code though that you need to fix (like undeclared variables, surplus comma, logic).
There seems to be a bunch of issues in the code you've supplied, for example #timein1 and #addvalue are not declared.
So here's a simple example:
DECLARE #time AS TIME = '08:00:00'
SELECT #time AS OriginalTime,
DATEADD(HOUR, 4, #time) TimePlus4Hours
Produces:
OriginalTime | TimePlus4Hours
====================================
08:00:00.0000000 | 12:00:00.0000000
Reference:
DATEADD (Transact-SQL)
Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date.
DATEADD (datepart , number , date )
Try by Changing the DATEADD() function syntax like this:
set #addvalue =(DATEADD(HH,4,#timein1))
I am storing all my dates in SQL Server Datetime fields in UTC Date.
There is a requirement where by I have to calculate local Datetime in a procedure from the UTC Date field, and for that i have the Time zone offset of the local datetime.
For ex. my Timezone offset is:'05:30:00'
and UTC Date is: 2013-02-09 08:34:12.037
Desired output: 2013-02-09 14:04:12.037
Now is there a simple way where of doing this without DateAdd and splitting the offset in hours and minutes.
You should be able to use the SWITCHOFFSET function. Here is an example:
declare #dt datetime;
set #dt = '2013-02-09 08:34:12.037';
select SWITCHOFFSET(CONVERT(datetimeoffset, #dt), '+05:30') as 'DATETIMEOFFSET',
CAST(SWITCHOFFSET(CONVERT(datetimeoffset, #dt), '+05:30') as datetime) as 'DATETIME'
-- Outputs:
--
-- 2013-02-09 14:04:12.0370000 +05:30 2013-02-09 14:04:12.037
Use the convert with 112:
declare #d datetime
set #d = getdate()
declare #s nvarchar(20)
set #s = convert(varchar, #d, 112)
print #s
That string will have the year, month, seconds etc.. always on the same position
Extract the desired part with substring:
print substring(#s, 1, 4) -- the year
Now recalculate the entire thing to minutes, by multiplying the hours by 60 and adding the minutes. Now substract your minutes delta from that number. Build a new string with the adjusted date-time, and convert that back to datetime. But... if you need to know the date as well, and you want to do it correct.... there is some coding left.
My advice: do use dateadd it's simple and correct (substract minutes is my advice).