SQL Server Date comparison throws error - sql

Please help on this, how independent query works but comparison is failing for below code,I am trying to compare only dates not time so tried the query like this.
SELECT CAST(getdate() AS DATE)---'2/9/2017 12:00:00 AM'
SELECT CAST('2017/01/15' AS DATE)----'1/15/2017 12:00:00 AM'
SELECT CAST(getdate() AS DATE) > CAST('2017/01/15' AS DATE); -- Error SQLSTATE 42000

You need to put this condition into context. For instance like this
SELECT case when CAST(getdate() AS DATE) > CAST('2017/01/15' AS DATE)
then 1
else 0
end

Try something like this:
DECLARE #nowDate DATE
SELECT #nowDate = CAST(getdate() AS DATE)
DECLARE #otherDate DATE
SELECT #otherDate = CAST('2017/01/15' AS DATE)
SELECT DATEDIFF(DAY, #nowDate, #otherDate)

SELECT CAST(getdate() AS DATE)---'2/9/2017 12:00:00 AM'
SELECT CAST('2017/01/15' AS DATE)----'1/15/2017 12:00:00 AM'
SELECT IIF(CAST(getdate() AS DATE) > CAST('2017/01/15' AS DATE),1,0); --good, you must use iif (or case when ) for predicates

You cannot compare in SELECT, you can use below code to determinate if date is greater or not than current date, or it is today.
DECLARE #DATE NVARCHAR(20) = '2017/01/15'
IF (CAST(getdate() AS DATE) > CAST(#DATE AS DATE))
PRINT 'Selected date is in past'
ELSE IF (CAST(getdate() AS DATE) = CAST(#DATE AS DATE))
PRINT 'Selected date is today'
ELSE
PRINT 'Selected date is in future'

You can try DATEDIFF() to find out difference between 2 dates.
select DATEDIFF( DAY,(CAST('2017/01/15' AS DATE)) ,(CAST(getdate() AS DATE)))

Related

SQL Check Current time is between two DATETIME columns

I need to check whether the current time is between two datetime column values.
And I only need to check the time is between the range and I don't want to check the date.
I know how to check a date is exists between a daterange like below
SELECT
*
FROM
Table1 T
WHERE
CAST(GETDATE() AS DATE) BETWEEN T.StartDate AND T.EndDate
We have stored start date and end date as folllows..
StartDate - 1900-01-01 08:00:00.000
EndDate - 1900-01-01 19:00:00.000
Is there something similar to this to check whether the time is exists in a date range?
if you only want to check time
SELECT *
FROM Table1 T
WHERE CAST(GETDATE() AS TIME) BETWEEN cast(T.StartDate as TIME) AND cast(T.EndDate as TIME)
Something like this I guess
declare #d1 datetime ='20171220 10:00'
, #d2 datetime = '20171220 12:00'
, #t time ='11:00';
select 'Yes' where #t between cast(#d1 as time) and cast(#d2 as time);
It worked when I tried like below
SELECT *
FROM Table1 T
WHERE CAST(GETDATE() AS TIME) BETWEEN CAST(T.StartDate AS TIME) AND CAST(T.EndDateAS TIME)
CONVERT() to TIME and then back to DATETIME and compare
WHERE CONVERT(DATETIME, CONVERT(TIME, GETDATE()))
BETWEEN T.StartDate AND T.EndDate

How to get data for the last week data?

I am trying to write a report whereby the report will have the contract updated records for the past week using ms sql script. Every Monday the report will be sent for the last Mon-sun. I tried the below query. it doesnt seems to work. Any idea how to achieve this?
SET DATEFIRST 1
select distinct [...]
where CONTRACT_UPDATE_DATE>= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND CONTRACT_UPDATE_DATE< dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
Thanks.
select * from table_abc WHERE
CAST(CONTRACT_UPDATE_DATE as date) between
CAST(DATEADD(dd, -7, GETDATE()) as date) and
CAST(GETDATE() AS DATE)
use dateadd to get 1 week before current date.
You can remove the cast as date if you need to validate by timestamp also.
You can try this,
SELECT Created_Date
FROM sample1
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
I suggest this solution:
select * from DB where Datediff(day, CONVERT(DATE, Sysdatetime()),
CONVERT(DATE, CONTRACT_UPDATE_DATE))<=7 and Datediff(day, CONVERT(DATE, Sysdatetime()),
CONVERT(DATE, CONTRACT_UPDATE_DATE))>0
You could try to achieve this by using the calender week.
Try the following:
-- Get last calendar week in format JJJJWW
DECLARE #jjjjkw varchar(6)
SELECT #jjjjkw =
CONVERT(varchar, DATEPART(YYYY,GETDATE()-7)) +
CASE WHEN LEN(CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7))) = 1 THEN '0'
+ CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7))
ELSE CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7)) END
-- Compare with the calendar week of your data-set
SELECT DISTINCT [...]
WHERE
CONVERT(varchar, DATEPART(YYYY,CONTRACT_UPDATE_DATE)) +
CASE WHEN LEN(CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE))) = 1
THEN '0' + CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE))
ELSE CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE)) END = #jjjjkw
Maybe not the most elegant way but it should work.

SQL DATEDIFF of am pm

i want to calculate the time difference between two times, but my problem is maybe the second time will be after midnight, and the first before it like:
time 1 = '2015-08-02 09:30 PM'
time 2 = '2015-08-03 02:30 AM'
so in this case the difference between them will be negative,
i try to multiply the value returned by -1 to convert it to positive value, but other data will be wrong..
my code is:
DECLARE #StartDate datetime = '2015-08-02';
DECLARE #EndDate datetime = '2015-08-02';
DECLARE #EmpID nvarchar(6) = '12345';
SELECT
SUM(CASE WHEN(DATEDIFF(minute, a.[Time], #StartDate)) < 0
then DATEDIFF(minute, a.[Time], #StartDate) * -1
ELSE DATEDIFF(minute, a.[Time], #StartDate) END
)
FROM
Attendance a
WHERE
(EmpID = #EmpID OR #EmpID IS NULL)
AND a.[date] <= #EndDate
GROUP BY EmpID
so how can i solve it?
I don't see anything wrong in your code. But i would use this syntax instead:
SUM(ABS(DATEDIFF(minute, a.[Time], #StartDate)))
I think that the following:
CASE WHEN a.[Time] > #StartDate
THEN DATEDIFF(minute,#StartDate,a.[Time])
ELSE DATEDIFF(minute,a.[Time],#StartDate)
END
Should do it and will always give a positive value.
select datediff(minute, '2015-08-02 09:30 PM' ,'2015-08-03 02:30 AM')
Returns 300, which is correct (5 hours, 5 * 60 =300)

SQL select where startdate is today's date

I am trying to write a query where the clause is when the start date for an employee is todays date.
select * from tbl_employees
where Startdate = getdate()
The issue is that Startdate is '2014-12-09 00:00:00.000'
and the function getdate is coming back with the date and time like '2014-12-09 08:25:16.013'
How can I write a query that only consider's the date?
You want just the date portion. The easy way is:
select *
from tbl_employees
where cast(Startdate as date) = cast(getdate() as date);
However, if you want to use an index, it is best not to have the column in a function call. So, this is better:
where (StartDate >= cast(getdate() as date) and StartDate < cast(getdate() + 1 as date))
select * from tbl_employees
where CONVERT(VARCHAR(10),Startdate,110) = CONVERT(VARCHAR(10),GETDATE(),110)
You can use to compare only DATE section not time..some thing like
IF CAST(DateField1 AS DATE) = CAST(DateField2 AS DATE)
OR
CONVERT(VARCHAR(10), GETDATE(), 112)
SELECT CONVERT (date, SYSDATETIME())
,CONVERT (date, SYSDATETIMEOFFSET())
,CONVERT (date, SYSUTCDATETIME())
,CONVERT (date, CURRENT_TIMESTAMP)
,CONVERT (date, GETDATE())
,CONVERT (date, GETUTCDATE());
/* Returned
SYSDATETIME() 2007-05-03
SYSDATETIMEOFFSET()2007-05-03
SYSUTCDATETIME() 2007-05-04
CURRENT_TIMESTAMP 2007-05-03
GETDATE() 2007-05-03
GETUTCDATE() 2007-05-04
*/
From: http://msdn.microsoft.com/en-us/library/ms188751.aspx
So using any of these will give you just the date

TSQL SELECT previous date's records

I want to select all records from a table Log where the DateAndTime field values (of type datetime) are for the day before today, whatever day it is.
So if today is 2011-06-08, I want to select all rows where DateAndTime is greater than or equal to 2011-06-07 00:00:00 and also less than 2011-06-08 00:00:00.
I'm guessing the potential pitfall here would be it's behaviour on the 1st day of the month, as obviously a date like 2011-06-00 is invalid, and should be 2011-05-31.
For SQL Server 2008 you can use this.
select *
from [log]
where cast(DateAndTime as date) = cast(getdate()-1 as date)
Pre 2008 you can use this
select *
from [log]
where DateAndTime >= dateadd(d, datediff(d, 0, getdate())-1, 0) and
DateAndTime < dateadd(d, datediff(d, 0, getdate()), 0)
Related on DBA: Cast to date is sargable but is it a good idea?
SELECT * FROM Log
WHERE DateAndTime >= DATEADD(DAY,-1, CAST(GETDATE() AS DATE))
AND DateAndTime < CAST(CAST(GETDATE() AS DATE) AS DATETIME)
This example assumes SQL Server:
select *
from log
where convert(varchar(8), DateAndTime , 112) = convert(varchar(8), getdate()-1, 112)
Essentially, convert the date to yyyymmdd (the 112 parameter) and then check it is equal to yesterday's date (getdate()-1), also converted to yyyymmdd.
Assuming SQL Server
declare #today date
set #today = GETDATE()
select * from Log where DateAndTime between DATEADD(dd, -1, #today ) and #today
It should include conditional operator and not between .
Otherwise it includes today's records as well.
Declare #today date
Set #today = GETDATE()
Select YourcolumnNames from log
Where DateAndTime >= DATEADD(dd, -1, #today ) and DateAndTime < DATEADD(dd, -1, #today )
Moreover, you should mention the column name and * should be avoided in the select statement. This can improve the performance