Please tell me what is error in my date comparison sql query - sql

Please help me to find out error in my SQL query. I have created this query to compare dates
select * from Joinplans jp
where cast(convert(varchar,GETDATE(),103) AS datetime) BETWEEN
CASE(convert(varchar,jp.planstartDate,103) AS datetime) AND
CASE(convert(varchar,DATEADD(DAY,jp.planDays,jp.planstartDate),103) AS DATETIME)
It's giving me the error:
incorrect near 'AS'
I am using SQL Server 2005.

You wrote case instead of cast in two instances.

If planStartDate is actually a date, then there is no need to cast it to a character column:
Select ...
From Joinplans jp
where GetDate() Between planStartDate And DateAdd(day, jp.planDays, jp.planStartDate)
Now, if planStartDate is storing both date and time data, then you might want to use something like:
Select ...
From Joinplans jp
Where planStartDate <= GetDate()
And GetDate() < DateAdd(day, jp.planDays + 1, jp.planStartDate)
This ensures that all times on the last date calculated via the DateAdd function are included

Related

SQL Server error in conversion of date from string

NPD.CreatedOn is defined as a datetime datatype column (in SQL Server).
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(MONTH, CONVERT(VARCHAR(7), NPD.CreatedOn, 126), CONVERT(VARCHAR(30), GETDATE(), 126)) <= 6
I get this error:
Conversion failed when converting date and/or time from character string.
What can I try to resolve it?
Don't use things like DATEDIFF in the WHERE on your columns, such queries aren't SARGable and thus can (will) perform poorly. If you want rows where the date is on or after the start of the month 6 months ago then do the date logic on GETDATE()/SYSDATETIME()/etc:
SQL Server doesn't have a "start of month" function, but you can use EOMONTH and then add a day:
SELECT *
FROM dbo.NPDMaster NPD
WHERE NPD.CreatedOn >= DATEADD(DAY, 1, EOMONTH(GETDATE(),-7));
You don't need to convert the datetime values to text. DATEDIFF() expects datetime values as second and third argument:
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(month, NPD.CreatedOn, GETDATE()) <= 6
The actual reason for the error (as is explained in the documentation), is that ...DATEDIFF implicitly casts string literals as a datetime2 type.

SQL Server: Inconsistencies in date

create table #temp
(
A date
)
insert into #temp(A)
values(GETDATE())
insert into #temp(A)
values(GETDATE()-1)
Now when I query the table as
select A from #temp where A>=GETDATE() and A<=GETDATE()
I get no records
But GETDATE() record value should satisfy my where condition, shouldn't it at least pass me one record?
Please guide me if I am missing some point here.
You need to do conversion, so it seems :
where a >= convert(date, dateadd(day, -1, getdate())) and
a <= convert(date, getdate());
Your where clause comparing date as :
where a >= '2020-04-21 16:01:27.277' and a <= '2020-04-21 16:01:27.277'
So, you need to convert date because getdate()will also return time portions.
Since your where clause looks for single day so you can do :
where a = convert(date, getdate())
Yogesh is right.
GETDATE() gives the present DATEIME value. When you insert it into a DATE column, SQL Server coerces -- silently typecasts -- the DATETIME to a DATE before inserting it.
But when you use it in a WHERE clause, SQL Server coerces the DATE from your column into a DATETIME value by turning 2020-04-20 into 2020-04-20 00:00:00. That can't be the same as GETDATE() except during the first few milliseconds of each day. (Meaning you or your test krewe are extremely unlikely to catch it equal.)

Subtract two dates in Microsoft SQL Server

I want to subtract 2 dates in MS SQL Server.
Example:
Current date Last used date
'2016-03-30' '2015-02-03'
Current date refers to today's date, "Last used date" is a measure.
How to write a query in SQL Server?
I have this but doesn't work (it says "Operand data type is invalid for subtract operator")
select
CONVERT(DATE, GETDATE()) - CONVERT(DATE, LastUsedDate)
from
databasename
SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate
Output DiffDate 61
More practice please refer below W3 school:
https://www.w3schools.com/sql/func_sqlserver_datediff.asp
Here you don't have to cast GETDATE() to date, as it is already datetime datatype. So your query will be as follows
SELECT DATEDIFF(day,CAST(LastUsedDate as date),GETDATE()) AS DifferneceDays
FROM TableName
The normal function to use is datediff():
select datediff(day, cast('2016-02-03' as date), cast('2016-03-30' as date))
You can subtract datetime values, but not dates. Alas.

Convert a varchar YYYYMMDD into datetime to compare with GETDATE()

What am I doing wrong here? I've looked through other posts but I'm getting different results than other people.
Trying to convert a varchar YYYYMMDD to datetime, and I keep getting:
Msg 8115, Level 16, State 2, Line 2
Arithmetic overflow error converting expression to data type datetime.
Attempts:
CONVERT(DATETIME, EXPDATE)
CONVERT(DATETIME, EXPDATE, 102)
(CONVERT(DATETIME, CAST(EXPDATE AS CHAR(8)), 112))
CONVERT(DATETIME, CAST(expdate AS VARCHAR(8)))
Am I bungling something obvious here?
You clearly have a values that are not valid dates.
In SQL Server 2012+, I would suggest TRY_CONVERT():
TRY_CONVERT(DATETIME, EXPDATE)
Then, look at the values that are NULL to see where data problems may be.
In earlier versions, you should be able to use isdate():
(CASE WHEN ISDATE(EXPDATE) = 1 THEN CAST(EXPDATE AS DATE) END)
I have a similarly formatted date field (DateKey) in a table I use. I convert it to DATETIME using this syntax:
SELECT CAST(CAST(DateKey AS VARCHAR(10)) AS DATETIME) FROM tblDate
Will this work for you?
Excellent. Gordon and chancrovsky, you helped me flush out the values that were formatted incorrectly. I used a version of what you posted and this worked
(CASE WHEN ISDATE(ExpDate) = 1 THEN CAST(ExpDate AS DATE) ELSE NULL
END) as ExpDate
Thank you so much!

'DATE' is not a recognized built-in function name

I wish to find all records of the current day. I have a field Date of type DATE.
I am getting error on sql server
'DATE' is not a recognized built-in function name.
on this line
(DATE(EnterDate) = CURDATE() )
As the error states, there is no DATE function in SQL Server 2008 or 2012 (you tagged both so I'm not sure which you're targeting). You can, however, cast to a date type in SQL Server 2008 and above:
WHERE EnterDate = CONVERT(date,GETDATE())
Note that there's no CURDATE function either, so I've translated that to GETDATE()
Use the following condition in your where cluase
WHERE CAST(DateColumn AS DATE) = CAST(GETDATE() AS DATE)
^------------ Your Column Name with `Date` or 'DateTime' data type
CURDATE() is a mysql function, In Sql-Server we have GETDATE() function to get current date and time.
More efficient one is
WHERE EnterDate > DATEADD(dd, -1, DATEDIFF(dd, 0, GETDATE()))
Thanks #D Stanley #marc_S and #Mihai
Finally I get it done by
WHERE EnterDate > Convert(DATETIME,Convert(varchar,DATEADD(DAY,0,GETDATE()),101))
This is not the exact answer but example how to trim the time part from the date time variable
CONVERT(VARCHAR(10),date_manufactured,10) =CONVERT(VARCHAR(10),#startdate,10))