I am working on a timetable and so I want to run a query which performs a check in the database to see all classes between a certain StartTime and EndTime. The user will select a start and end time for a class which will be stored in a label as a DateTime format 02/03/2017 00:00:00.
I want to run a query to check for a class so I want to use the selected start time to see if class is greater or equal to this start date but less than the next day 03/03/2017 00:00:00. The below query works fine but I will be using parameterised values.
My current query is:
SELECT * FROM Class WHERE (StartTime >='02/03/2017 00:00:00') AND ( EndTime <= '03/03/2017 00:00:00' )
My desired query with parameters:
SELECT * FROM Class WHERE (StartTime >='#StartTime') AND ( EndTime <= '#EndTime' )
You have quotes around the #StartTime and #EndTime. Remove those, so something like below should give you the correct results.
declare
#StartTime datetime = '2017-03-02 00:00:00.000',
#EndTime datetime = '2017-03-03 00:00:00.000'
SELECT * FROM Class WHERE (StartTime >=#StartTime) AND ( EndTime <= #EndTime )
Also to address your new requirement of
I just want to increment the value of the start time by 1 day
here is the code
declare
#StartTime datetime = '2017-03-02 00:00:00.000'
-- Add 1 day to start time to get the end date.
declare
#EndTime datetime = dateadd(day, 1, #StartTime)
SELECT * FROM Class WHERE (StartTime >=#StartTime) AND ( EndTime <= #EndTime )
Try without the single quotes:
SELECT * FROM Class WHERE (StartTime >=#StartTime) AND ( EndTime <= #EndTime )
you can declare StartTime and EndTime and your request be:
SELECT * FROM Class WHERE (StartTime >=#StartTime) AND ( EndTime <= #EndTime )
You must remove the quotes
SELECT * FROM Class WHERE (StartTime >=#StartTime) AND ( EndTime <= #EndTime )
Your query tries to parse a date out of the string "#EndTime"
declare #startTime datetime;
declare #endTime datetime;
set #startTime = cast(getdate() as date); -- sets start time to start of current day
set #endTime = dateadd(day,1,#startTime); -- sets end date to one day past start date
SELECT * FROM Class WHERE (StartTime >=#StartTime) AND ( EndTime < #EndTime ) -- use < for value to be less than next day
Related
This query is driving me crazy, any help is appreciated.
I have a table as follows:
CREATE TABLE Bookings
(
Id bigInt IDENTITY(1,1),
hallId bigInt,
startTime smallDateTime,
endTime smallDateTime
)
INSERT INTO Bookings
VALUES (1, '2022-10-03 08:00:00', '2022-10-03 10:00:00')
--Edit( One of my trials so far
DECLARE #startTime AS SmallDateTime = '2022-10-03 08:00:00'
DECLARE #endTime AS SmallDateTime = '2022-10-03 10:0:00'
DECLARE #hallId AS bigInt = 1
SELECT * FROM Bookings WHERE
startTime >= FORMAT(#startTime, 'yyyy-dd-MM HH:mm:ss') OR startTime <= FORMAT(#endTime, 'yyyy-dd-MM HH:mm:ss') AND
endTime >= FORMAT(#startTime, 'yyyy-dd-MM HH:mm:ss') OR endtime <= FORMAT(#endTime, 'yyyy-dd-MM HH:mm:ss')
AND hallId=#hallId
-- Also this Way
DECLARE #startTime AS SmallDateTime = '2022-03-10 08:00:00'
DECLARE #endTime AS SmallDateTime = '2022-03-10 10:0:00'
DECLARE #hallId AS bigInt = 1
SELECT * FROM Bookings WHERE
startTime >= #startTime OR startTime <= #endTime
AND
endTime >= #startTime OR endtime <= #endTime
AND hallId=#hallId
--Edit)
My Datetime format is 'yyyy-MM-dd HH:mm:ss' but it's records are entered in yyyy-dd-MM HH:mm:ss format
So what I want is a query that checks for 2 datetime ranges (say 2022-10-03 08:00:00 - 2022-10-03 10:00:00), if there is a match it returns the data otherwise it returns nothing.
My goal is to check if either of the startTime OR endTime falls within an existing Booking (e.g None of startTime or endTime can't be within '2022-10-03 08:00:00' up to '2022-10-03 10:00:00'), if found, the booking can't precede unless he/she has to alter. I tried between, but seems to work one way and fails another
It would be a plus if someone could check in separately that is to display a specific message/status for startTime and endTime (I mean if the startTime corresponds to existing Booking msg='Select a different start time' and if The endTime corresponds to existing Booking msg='Select a different end time'
Also I tried to check if the difference of startTime and endTime is less then 1 hour.
BWT, I'm using SQL Server 2014 Express
You can do INSERT...SELECT...WHERE NOT EXISTS, then check the rowcount afterwards. To compare for interval overlap, compare one start time with the other end, and the reverse.
Note that you should always specify column names for inserts, and pass values as parameters, not text.
INSERT INTO Bookings (hallId, startTime, endTime)
SELECT #hallId, #startTime, #endTime
WHERE NOT EXISTS (SELECT 1
FROM Bookings b WITH (UPDLOCK) -- needs UPDLOCK to prevent race conditions
WHERE b.hallId = #hallId
AND b.startTime < #endTime
AND b.endTime > #startTime
);
IF ##ROWCOUNT = 0
THROW 50001, N'Overlapping booking exists', 1;
You may want to change to <= if you don't want to allow two intervals to abut.
Thanks to who ever tried to help, I figured it out,
Sometimes all you need is to take a quick break.
I found out that smallDateTime data type was acting crazy, it was swapping the month and the day while inserting in the table
e.g if I Inserted 2022-03-15 20:00:00 it would be recorded as 2022-15-03 20:00:00 and vice-versa
So Here goes what worked for me, It may help someone in the nearer or far future
-- 2022-03-11 13:30:00, 2022-03-11 15:00:00 => sample data 1 in the table
-- 2022-03-11 09:30:00, 2022-03-11 12:30:00 => sample data 2 in the table
DECLARE #startTime AS SmallDateTime = '2022-03-11 15:01:00'
DECLARE #endTime AS SmallDateTime = '2022-03-11 19:30:00'
DECLARE #hallId AS bigInt = 1
SELECT * FROM Bookings WHERE
(startTime BETWEEN #startTime AND #endTime) OR
(endTime BETWEEN #startTime AND #endTime) AND hallId=#hallId
I am having a little trouble figuring out how to write a query that seems pretty straight forward.
The problem is in my WHERE clause. There are two fields in my table. A timestamp for when the task has started startTime and a timestamp for when the task was completed endTime/ Both of these fields are Datetime.
In my UI, I allow the person to select a Start Date and End Date and their filtering option.
The date logic should be as follows:
Everything where the StartTime is >= #startDate but < #endDate and the EndTime is <=#endDate but > #startDate.
I have done date ranges before using a single date in the database but not multiple so I am confused.
Any thoughts?
-- Fetch our data
SELECT [recordID],
[ItemID],
[QID],
[NTID],
[EmpID],
[FirstName],
[LastName],
[SupQID],
[SupEmpID],
[SupFirstName],
[SupLastName],
[Location],
[Department],
[Skillset],
[BudgetMarket],
CONVERT (VARCHAR (20), [startTime], 100) AS startTime,
CONVERT (VARCHAR (20), [endTime], 100) AS endTime,
COALESCE (DATEDIFF(SECOND, startTime, endTime), 0) AS totalTimeSeconds
FROM itemTracker_records
WHERE (#employee IS NULL OR (QID = #employee))
AND (#supervisor IS NULL OR (supQID = #supervisor))
AND CAST(endTime as Date) >= #startDate AND CAST(endTime as Date) < #endDate
FOR XML PATH ('results'), TYPE, ELEMENTS, ROOT ('root');
Shouldn't it be as simple as :
WHERE (StartTime >= #startDate AND #startDate < #endDate )
AND (EndTime <= #endDate AND #endDate > #startDate)
Or, slightly shorter:
WHERE StartTime between #startDate AND #endDate
AND EndTime between #startDate AND #endDate
Assuming "good" data, i.e. tasks always end after they start and the user supplied range is valid:
where startTime >= #StartDate and endTime <= #EndDate
As long as that is true then the task time span must be contained within the user specified range.
Note that a common problem is attempting to find date/time values between a pair of dates. To include all times on the last day it is necessary to add one day to #EndDate and remove equality from the comparison.
How can I create a method to subtract two dates and this is equal to in real date as format datetime2(7) in sql server 2008.
For example ,I create this method:
Delete from TblMessage
Where MDateTime<((SELECT TOP (1)MDateTime FROM TblMessage ORDER BY MDateTime DESC)- ('2013-10-04 16:47:56.0000000'))
but it is not working .I want to result of subtract two date like this:
MDateTime1:2013-10-05 16:47:56.0000000
MDateTime2:2013-09-04 16:47:56.0000000
Result:2013-01-01 00:00:00.0000000
Result=MDateTime1-MDateTime2
How can I do this. Thanks...
Perhaps you are looking for this?
select DATEADD( day, datediff(day,GETDATE(), getdate() - 10), GETDATE() ) ;
DATEDIFF(dayofyear,MDateTime1,MDateTime2) AS Result
http://msdn.microsoft.com/en-us/library/ms189794.aspx
DECLARE
#DATE1 DATETIME = '2013-10-05 16:47:56.000',
#DATE2 DATETIME = '2013-09-04 17:37:42.000',
#DATEDIFF AS INT,
#BASEDATE DATETIME;
-- USE WHAT EVER DATE YOU WISH TO BE YOUR BASE DATE
SET #BASEDATE = '1/1/1900';
SET #DATEDIFF = DATEDIFF(SECOND, #DATE2, #DATE1);
SELECT #DATE1,#DATE2,#DATEDIFF, DATEADD(SECOND,#DATEDIFF,#BASEDATE)
Thus a scalar function could be created like this...
CREATE FUNCTION dbo.sf_GetMeasureDate
(
#EndDate DATETIME,
#StartDate DATETIME,
#BaseDate DATETIME
)
RETURNS DATETIME
AS
BEGIN
DECLARE #DATEDIFF AS INT
SET #DATEDIFF = DATEDIFF(SECOND, #StartDate, #EndDate);
Return DATEADD(SECOND,#DATEDIFF,#BASEDATE)
END
GO
Then within you regular SELECT statement you can call the function as such.
SELECT dbo.sf_GetMeasureDate('2013-10-05 16:47:56.000','2013-09-04 17:37:42.000','1/1/1900')
or within an existing query:
SELECT dbo.sf_GetMeasureDate([fld1],[fld2],'1/1/1900')
How do I calculate total minutes between start and end times? The Start/End times columns are nvarchar and I am declaring them as datetime. I'm not sure if that is my first step or not, I am new to SQL and to declaring.
The final goal is to take Total Minutes, subtract Lunch and Recess (both are minutes) and then multiply by 5 to get total instructional minutes for the week per school.
DECLARE #StartTime datetime, #Endtime datetime
SELECT --[School]
[GradeLevel]
,[StartTime]
,[EndTime]
,(#Endtime - #StartTime) AS 'TotalMinutes'
,[Lunch]
,[Resess]
,[Passing]
FROM [dbo].[StartEndTimes]
Current Output:
GradeLevel StartTime EndTime TotalMinutes Lunch Resess Passing
2-5 7:50 14:20 NULL 20 10 NULL
K-5 7:45 14:20 NULL 20 10 NULL
K-5 7:50 14:20 NULL 20 10 NULL
Maybe something like this is what you want?
select (datediff(minute, starttime, endtime) -lunch -recess) * 5 AS TotalInstruct
from YourTable
If you want to sum it up for all rows then try:
select sum((datediff(minute, starttime, endtime) -lunch -recess) * 5) AS TotalInstruct
from YourTable
If you want to get the number of hours per school you would have to include the schoolfield in the query and use it in the group byclause, and then the query becomes this:
select school, sum((datediff(minute, starttime, endtime) -lunch -recess) * 5) AS TotalInstruct
from YourTable
group by school
Sample SQL Fiddle for the above queries.
If all you want is to find the difference between two dates then you can use DATEDIFF function (http://msdn.microsoft.com/en-us/library/ms189794.aspx)
Example:
DECLARE #startdate datetime2
SET #startdate = '2007-05-05 12:10:09.3312722';
DECLARE #enddate datetime2 = '2007-05-04 12:10:09.3312722';
SELECT DATEDIFF(MINUTE, #enddate, #startdate);
If however your values are in string format you need to convert them prior to passing them to the DATEDIFF function.
Example:
DECLARE #starttexttime nvarchar(100)
SET #starttexttime = '7:50'
DECLARE #starttime datetime2
SET #starttime = CONVERT(datetime2, #starttexttime, 0)
DECLARE #endtexttime nvarchar(100)
SET #endtexttime = '17:50'
DECLARE #endtime datetime2
SET #endtime = CONVERT(datetime2, #endtexttime, 0)
SELECT DATEDIFF(MINUTE, #starttime, #endtime);
How can I get the total minute for sql datetime?
Let's say:
select getdate() from table
In this way, I will get everything, but I only want to get total minute. For eg,
if the time is 07:10:35, I want 430.
How to achieve that?
The value from the field is 01-01-2001 07:10:40
The result I want is 430 ((7*60)+10) only.
Here's a sample:
DECLARE #dt datetime
SET #dt = '01-01-2001 07:10:20'
SELECT DATEDIFF(MINUTE, DATEADD(DAY, DATEDIFF(DAY, 0, #dt), 0), #dt)
(DATEPART(HOUR,GETDATE()) * 60) + DATEPART(MINUTE,GETDATE())
This query will return the number of minutes past midnight.
declare #now datetime = getdate()
declare #midnight datetime = CAST( FLOOR( CAST( #now AS FLOAT ) ) AS DATETIME )
select datediff(mi, #midnight,#now)
The code
CAST( FLOOR( CAST( "yourDateTimeHere" AS FLOAT ) ) AS DATETIME )
converts any datetime to midnight. Use the datediff with the "mi" function to get the number of minutes past midnight.
Use books online for more date and time math