How to compare dates in SQL stored procedure? - sql

I want to query the database within a stored procedure with the following SQL statement:
SELECT date1 FROM table INTO dates
WHERE date1 < CONVERT(VARCHAR(8), GETDATE(), 112)
AND date1 > CONVERT(VARCHAR(8), DATEADD(DAY, -4, GETDATE()), 112);
I get an error on the WHERE clause, what am I doing incorrectly?

The syntax erro is because the INTO is wrong.
1) But as #Jonathan has mentioned , the funcitions GETDAT, CONVERT, DATEADD
aren't native and not exists at INFORMIX database. Unless you have create it...
2) The "dates" should be a variable at your SPL.
3) The SELECT should return only 1 row....
SELECT date1 INTO dates FROM table
WHERE date1 < CONVERT(VARCHAR(8), GETDATE(), 112)
AND date1 > CONVERT(VARCHAR(8), DATEADD(DAY, -4, GETDATE()), 112);
This should be a valid Informix syntax:
SELECT date1 INTO dates FROM table
WHERE date1 < today
AND date1 > today - 4 units day ;
For more information about the syntax , please check at the IBM Knowledge Center

Assuming date1 is datetime type then Use Between
SELECT date1 INTO dates FROM table
WHERE date1 BETWEEN CONVERT(VARCHAR(8), DATEADD(DAY, -4, GETDATE()), 112) AND
CONVERT(VARCHAR(8), GETDATE(), 112);
if date1 is not datetime, then convert it to then Use Between
SELECT date1 INTO dates FROM table
WHERE CONVERT(VARCHAR(8), date1, 112) BETWEEN CONVERT(VARCHAR(8), DATEADD(DAY, -4, GETDATE()), 112) AND
CONVERT(VARCHAR(8), GETDATE(), 112);

Related

Why Week conversion failed in SQL Server in my case?

I am trying to convert week of the date based on my criteria.
My date condition: if my #date is less than 4 AM, then #date - 1, else #date
declare #dates datetime
set #dates = '2019-01-01 03:59:59'
select
case
when convert(varchar(26), #dates, 108) <= '04:00:00'
then convert(varchar, dateadd(day, -1, #dates), 103)
else convert(varchar, #dates, 103)
end BusinessDate
Output:
31/12/2018 // as expected
Now I want to find the week number of the output. So I tried
declare #dates datetime
set #dates = '2019-01-01 03:59:59'
select
case
when convert(varchar(26), #dates, 108) <= '04:00:00'
then convert(varchar, dateadd(day, -1, #dates), 103)
else convert(varchar, #dates, 103)
end BusinessDate,
case
when convert(varchar(26), #dates, 108) <= '04:00:00'
then datepart(week, convert(datetime, convert(varchar, dateadd(day, -1, #dates), 103)))
else datepart(week, convert(datetime, convert(varchar, #dates, 103)))
end weeks
But I get this error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Just subtract four hours:
select datepart(week,
dateadd(hour, -4, #dates)
)

Sybase - Filter records with current date efficiently

I am trying to filter records based on current date (date part only) against a column "date_sent" which is a DateTime datatype. Though this can be written in multiple ways, I want to know which method will be the most efficient. The table has 11-12 millions of records ant any given time.
Let's say the current date is 16th April 2018
SELECT *
FROM TABLE_NAME
WHERE datepart(YEAR, date_sent) = 2018
AND datepart(MONTH,date_sent) = 4
AND datepart(DAY,date_sent) = 16;
SELECT *
FROM TABLE_NAME
WHERE convert(char(8), date_sent, 112) = convert(char(8), getdate(), 112);
Any other suggestions.
I would start with:
select *
from table_name
where date_sent >= dateadd(day, datediff(day, 0, getdate()), 0) and
date_sent < dateadd(day, 1 + datediff(day, 0, getdate()), 0)
The right hand side removes the time component of the current date. The comparisons should allow Sybase to still us an index on date_sent.
EDIT:
Perhaps Sybase doesn't permit 0 as a date value. You can also do:
select *
from table_name
where date_sent >= dateadd(day, datediff(day, cast('2000-01-01' as date), getdate()), cast('2000-01-01' as date)) and
date_sent < dateadd(day, 1 + datediff(day, cast('2000-01-01' as date), getdate()), cast('2000-01-01' as date))

I need to change the date output format on SQL withing this script from yyy-mm-dd to dd.mm.yyyy

SELECT DISTINCT [WHO].PERSONNUM EMPID
, [SHIFTSTARTDATE] STDT
, [SHIFTENDDATE] ENDDT
, GETDATE() [WHEN]
FROM [WFCDB].[dbo].[SHIFTASSIGNMNT] AS [WHN]
LEFT OUTER JOIN [WFCDB].[dbo].VP_ALLPERSONv42 AS [WHO]
ON [WHN].EMPLOYEEID = [WHO].EMPLOYEEID
WHERE DATEPART(m, [SHIFTSTARTDATE]) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, [SHIFTSTARTDATE]) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
AND DELETEDSW <> 1)
You can use CONVERT to format dates:
CONVERT(VARCHAR(20), GETDATE(), 104) --> dd.mm.yy
Take a look at MS Docs
But I usually format my dates in the presentation layer.
You can use this
SELECT convert(varchar, getdate(), 104)
check this link other formats
https://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/

TSQL Date conditions

I have a table of events, constantly being updated, with a datetime column.
I want to get all events that start today as well as the ones that start 8 hours into the next day.
The idea is that people don't really check in the middle of the night for events, so we list them in the day before.
To get today's I do DATEDIFF(day,eventdate,GETDATE())=0 but I havn't figured out how to do the dateadd() for my case. I either get no rows or too many.
So the wanted result is:
From 00:00 on March 9 to 8:00 on March 10. (example only)
It is better to not do any calculation on your column. Calculate the interval instead and fetch the rows that is in the interval. That way you can make use of a index on eventdate instead of doing a table scan.
select SomeColumns
from YourTable
where eventdate >= dateadd(day, datediff(day, 0, getdate()), 0) and
eventdate < dateadd(hour, 32, dateadd(day, datediff(day, 0, getdate()), 0))
You can use these to bound your query...
DECLARE #Start DateTime = CONVERT(nvarchar(10), GetDate(), 121)
DECLARE #End DateTime = DATEADD(Hour, +32, #Start)
Here's a Test Script
CREATE TABLE #Temp (Column1 DateTime)
INSERT INTO #Temp (column1) values (getdate()) -- it's 6pm now
INSERT INTO #Temp (column1) values (dateadd(hour, -24, getdate())) --6pm yesterday - outside window
INSERT INTO #Temp (column1) values (dateadd(hour, -12, getdate())) --6am today
INSERT INTO #Temp (column1) values (dateadd(hour, -5, getdate())) -- 1pm today
INSERT INTO #Temp (column1) values (dateadd(hour, +12, getdate())) -- 6am tomorrow - inside window
INSERT INTO #Temp (column1) values (dateadd(hour, +17, getdate())) -- 11am tomorrow - outside window
select * from #Temp
DECLARE #Start DateTime = CONVERT(nvarchar(10), GetDate(), 121)
DECLARE #End DateTime = DateAdd(Hour, +32, #Start)
SELECT * FROM #Temp WHERE Column1 > #Start AND Column1 < #End
SELECT
Column1, Column2
FROM
TableName
WHERE
DateColumm BETWEEN Convert(Date, GETDATE()) AND DateAdd(hh, 32, Convert(smalldatetime, Convert(Date, GETDATE())))
You can also do it this way:
select *
from yourtable
WHERE EventDate >= Convert(varchar(10), getdate(), 101)
AND EventDate < CAST(Convert(varchar(10), DateAdd(d, 1, getdate()), 101) + ' 08:00 AM' as datetime)
Then if you EventDate has the time on it, then you can convert the EventDate in the first part of your WHERE clause
select *
from yourtable
WHERE Convert(varchar(10), EventDate, 101) >= Convert(varchar(10), getdate(), 101)
AND EventDate < CAST(Convert(varchar(10), DateAdd(d, 1, getdate()), 101) + ' 08:00 AM' as datetime)
You can try something like this.
The DateAdd documention page shows all the different date parts you can use (hour, day, seconds, etc.)
DECLARE #StartTimeWindow DATETIME, #EndTimeWindow DATETIME
SET #StartTimeWindow = DATEDIFF(DAY, 0, GETDATE())
SET #EndTimeWindow = DATEADD(HOUR, 32, #StartTimeWindow)
SELECT *
FROM EventTable
WHERE EventDate >= #StartTimeWindow
AND EventDate <= #EndTimeWindow

SQL query in SQL SERVER 2005 - Comparing Dates

I'm having a hard time doing this query.
I want to compare dates in my query, dates from my DB are in this format:
(MM/DD/YYYY HH:MM:SS AM)
I want to compare this date with tomorrow's day, today plus one.
My questions are:
How do I declare tomorrow's date in sql server?
How would you compare these two dates?
Thank you!! =D
EDIT : DATES in DB are VarChar =S
declare tomorrow's date : DATEADD(dd,1,getdate())
compare dates :
WHERE column >= CONVERT(datetime, CONVERT(varchar, DATEADD(day, 1, GETDATE()), 102))
AND column < CONVERT(datetime, CONVERT(varchar, DATEADD(day, 2, GETDATE()), 102))
Assumes datetime datatype for columns
WHERE
MyCol >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1)
AND
MyCol < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 2)
This (yyyy-mm-dd) removes the time component to test of MyCol is tomorrow
2009-10-06 00:00:00 <= MyCol < 2009-10-07 00:00:00
You don't strip time from MyCol: this will affect performance and disallow index usage etc
Efficiency of remove time from datetime question, which is why I used this format and avoid varchar conversions...
Edit:
Avoiding implicit conversions and string matching
10/06/2009 <= MyCol < 10/07/2009
WHERE
MyCol >= CONVERT(char(10), DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1), 101)
AND
MyCol < CONVERT(char(10), DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 2), 101)
Of course, it'll fail at the end of December...
I would think your dates are most likely to be in SQL Server's datetime datatype, and that the format you give is just the default string representation.
Typically, I use something like:
SELECT *
FROM tbl
WHERE datecol = CONVERT(datetime, CONVERT(varchar, DATEADD(day, 1, GETDATE()), 101))
However, if your datetimes include a time piece, you need to use something like this:
SELECT *
FROM tbl
WHERE datecol >= CONVERT(datetime, CONVERT(varchar, DATEADD(day, 1, GETDATE()), 101))
AND datecol < CONVERT(datetime, CONVERT(varchar, DATEADD(day, 2, GETDATE()), 101))
There are other date arithmetic tricks you can use. There are plenty here on SO if you look for SQL dates
SQL Server allows you to declare variables
DECLARE #TomorrowsDate DateTime
And you can set it to the current date and time
SET #TomorrowsDate = DATEADD (Day, 0, GETDATE())
For tomorrow's date (without time)
SET #TomorrowsDate = DATEADD (Day, 1, CONVERT (VARCHAR, GETDATE(), 101))
To use it in a query with a column without declaring a variable
SELECT Column1, Column2
FROM YourTableName
WHERE DateColumn BETWEEN DATEADD (Day, 0, CONVERT (VARCHAR, GETDATE(), 101))
AND DATEADD (Day, 1, CONVERT (VARCHAR, GETDATE(), 101))