I have the following table in sql server 2008 (Called "act_events"):
As you notice some of the datetimes are formated: "yyyy-mm-dd" and some: "yyyy-dd-mm" for some weird reason I still haven't figured..
I have a query as follows:
SELECT * from act_events
WHERE '2013-07-30'>=(CAST(e_start as DATE)) AND
'2013-07-30'<=(CAST(e_end as DATE))
Where I want to select events only with today's date.
But I can't figure a way to select both formats..
I tries this query:
SELECT * from act_events
WHERE( #date1>=(CAST(e_start as DATE)) AND
#date2<=(CAST(e_end as DATE)) ) OR
( #date3>=(CAST(e_start as DATE)) AND
#date4<=(CAST(e_end as DATE)) )
But it only works for certain dates..
Would appreciate your answers.
Also, if there's a statement that will change all datetime to correct format I would love to hear.
Assuming the dates are indeed of type DateTime, what you could do in this case is to use dateadd and datediff.
Run these two statements:
-- Todays date, date part only
select dateadd(dd, 0, datediff(dd, 0, getdate()))
-- Tomorrows date, date part only
select dateadd(dd, 0, datediff(dd, 0, dateadd(dd, 1, getdate())))
Using those two, you can do this (Including edits, thanks #gvee)
select *
from act_events
where
e_start >= dateadd(dd, 0, datediff(dd, 0, getdate()))
and
e_end < dateadd(dd, 0, datediff(dd, 0, getdate()) + 1)
I should mention that getdate() is a built-in function in SQL Server. You could of course change this to a variable if you are using this in a stored procedure for example.
As a side note, the date in SQL Server is actually a number. The format that comes out when you look at it is for humans and humans are not to be trusted, right?
select *
from t
where
CONVERT(nvarchar(30), GETDATE(), 112)=substring(date_c,1,4)
+substring(date_c,6,2)
+substring(date_c,9,2)
or
CONVERT(nvarchar(30), GETDATE(), 112)=substring(date_c,1,4)
+substring(date_c,9,2)
+substring(date_c,6,2)
SQLFiddle demo
Related
I have a where clause in a SQL statement that hard codes two dates using a between function. I would like to have those dates be more dynamic and update every year with out manually changing it. Using the GetDate function in some manner.
I have tried using variations of getdate and it does not work.
My current code looks like this
Where Date between '1/1/2018' and 1/1/2019'
I need this to update every year once a a new year starts in January.
Try this:
Where date between (SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)) And
(DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1))
For MS SQL Server you can use the below for the previous year's data;
WHERE [DateFieldName] BETWEEN DATEADD(YYYY, DATEDIFF(YYYY, 0, GETDATE()) -1, 0)
AND DATEADD(YYYY, DATEDIFF(YYYY, 0, GETDATE()),0)
For MS SQL Server 2012 and later you can use DATEFROMPARTS:
DECLARE #StartDate Date = DATEFROMPARTS(YEAR(GETDATE()),1,1)
DECLARE #EndDate Date = DATEFROMPARTS(YEAR(GETDATE())+1,1,1)
Then your query becomes:
SELECT *
FROM SomeTable
WHERE MyDate >= #StartDate AND MyDate < #EndDate
I wrote a query to obtain First of month,
SELECT DATEADD(DAY, -(DATEPART(DAY,GETDATE())-1), GETDATE()) as First_Of_Month;
for which i do get the appropriate output, but my time stamp shows the current time.
Here's what I am doing in the query, hope i make sense.
using datepart i calculated the no. of days (int) between the 1st and today (27-1 =26)
Then using dateadd function, i added "-datepart" to get the first of the month.
This is just changing the date, what should i look at or read about in order to change the time. I am assuming that it would have something to do with 19000101
For SQL Server 2012 (thanks adrift and i-one)
DECLARE #now DATETIME = CURRENT_TIMESTAMP;
SELECT DATEADD(DAY, 1, EOMONTH(#now, -1));
-- or
SELECT DATEFROMPARTS(YEAR(#now), MONTH(#now), 1);
For SQL Server 2008+
DECLARE #now DATETIME = CURRENT_TIMESTAMP;
-- This shorthand works:
SELECT CONVERT(DATE, #now+1-DAY(#now));
-- But I prefer to be more explicit, instead of relying on
-- shorthand date math (which doesn't work in all scenarios):
SELECT CONVERT(DATE, DATEADD(DAY, 1-DAY(#now), #now));
For SQL Server 2005
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),0);
A caveat if you're using this SQL Server 2005 method: you need to be careful about using expressions involving DATEDIFF in queries. SQL Server can transpose the arguments and lead to horrible estimates - as seen here. It might actually be safer to take the slightly less efficient string approach:
SELECT CONVERT(DATETIME, CONVERT(CHAR(6), GETDATE(), 112) + '01');
SELECT convert(varchar(10),DATEADD(DAY, - (DATEPART(DAY,GETDATE())-1), GETDATE()),120)+' 00:00:00' as First_Of_Month;
Just the date
DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
So for a month it is:
DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0) AS FirstDatetimeOfMonthmm,
I think the easiest way is to cast the result to date:
SELECT cast(DATEADD(DAY, -(DATEPART(DAY,GETDATE())-1), GETDATE()) as date) as First_Of_Month
One alternative:
SELECT cast(
cast(datepart(yyyy, getdate()) as varchar)
+ '-'
+ cast(datepart(mm, getdate()) as varchar) + '-01 00:00:00'
as datetime)
Build up the date from year/month components, then tack on the 1st and midnight.
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) as First_Of_Month;
Try following code:
SELECT CAST(CAST(GETDATE() AS DATE) AS DATETIME) AS StartDateTime,
DATEADD(ms, -3, CAST(CONVERT(date, DATEADD (DAY,1,GETDATE())) AS varchar(10))) AS EndDateTime
Result:
StartDateTime
EndDateTime
2022-05-23 00:00:00.000
2022-05-23 23:59:59.997
I need all the records from last day?
Hi
Select * from table1 where tabledate > getdate() -1
with this query, i need to run is exactly after midnight to get exact result. I need to run it in day time and get all the previous day's records.
In SQL Server 2005, this is generally the fastest way to convert a datetime to a date:
DATEADD(day, DATEDIFF(day, 0, yourDate), 0)
In your case, it's done only once, so the how doesn't really matter much. But it does give the following query.
Select
*
from
table1
where
tabledate >= DATEADD(day, DATEDIFF(day, 0, getDate()) - 1, 0)
AND tabledate < DATEADD(day, DATEDIFF(day, 0, getDate()), 0)
Check this page out. It is a great resource for calculating dates.
http://www.simple-talk.com/sql/learn-sql-server/robyn-pages-sql-server-datetime-workbench/#calculatingdates
Another method is to use DATEDIFF alone:
SELECT * FROM table1
WHERE DATEDIFF(DAY, tabledate, GETDATE()) = 1
A datediff of 1 for day covers any time in the previous day.
DECLARE #d SMALLDATETIME;
SET #d = DATEDIFF(DAY, 0, GETDATE());
SELECT <cols> FROM dbo.table1
WHERE tabledate >= DATEADD(DAY, -1, d)
AND tabledate < #d;
Try this:
your_field = cast(dateadd(D,-1,getdate()) as DATE)
In SQL Server 2008R2 fetching data between two dates is not working.
I am using the following code to get rows from the INVOICE table where the CREATED_DATE is between #startdate and #enddate, which are the parameters I am sending to the stored procedure.
Select *
from INVOICES INV
where CONVERT(Varchar(10), INV.CREATED_DATE, 105)
BETWEEN CONVERT(VARCHAR(10), #startdate, 105)
AND CONVERT(VARCHAR(10), #enddate, 105)
It is not working properly, driving me nuts..
What I am doing wrong?..
select * from
invoices inv
where inv.created_date >= dateadd(dd, 0, datediff(dd, 0, #startdate))
and inv.created_date < dateadd(dd, 1, datediff(dd, 0, #enddate))
First of all, do not convert your start/end and column's dates to varchar, and if you do so remember that 105 (returns dd-mm-yyyy) is not comparable, 112 (returns yyyymmdd) would be better (when you are interested in date part only). But what I've said it's better not to convert and just compare dates.
Added:
And little explanation: dateadd(dd, 0, datediff(dd, 0, #startdate)) - returns date part only of datetime, dateadd(dd, 1, datediff(dd, 0, #startdate)) - returns next day date part only.
Query returns all rows for your parameters inclusively (regardless of the hour).
Since you're on SQL Server 2008 R2, you could just convert everything to the DATE format:
SELECT *
FROM dbo.INVOICES INV
WHERE CAST(INV.CREATED_DATE AS DATE)
BETWEEN CAST(#startdate AS DATE) AND CAST(#enddate AS DATE)
Since you're using the DATE type, you're independent of any dateformat or language settings or any of those tricky features. SQL Server will just compare dates - as it should.
And of course: if you make your stored procedure parameters #startdate and #enddate to be of type DATE from the beginning, then you can save yourself those two CAST operations, too!
SELECT *
FROM dbo.INVOICES INV
WHERE CAST(INV.CREATED_DATE AS DATE) BETWEEN #startdate AND #enddate
(and if you made CREATED_DATE of type DATE - you could even forget about that last CAST in the statement, too!)
Default setting is yyyy-MM-dd
If you use 105 which means you're trying to parse date as format dmy, so before executing add below line at the top of your query.
SET DATEFORMAT DMY
I am trying to do this:
select * from table
where ChangingDate(this is a column which has date and time) = today's date + 1
I am a learner of SQL, and I am bad at date formats. I appreciate if someone can help.
Thank you!
This will return tomorrow's data
WHERE ChangingDate > = dateadd(dd, datediff(dd, 0, getdate())+1, 0)
and ChangingDate < dateadd(dd, datediff(dd, 0, getdate())+2, 0)
This will return today's data
WHERE ChangingDate > = dateadd(dd, datediff(dd, 0, getdate())+0, 0)
and ChangingDate < dateadd(dd, datediff(dd, 0, getdate())+1, 0)
See also How Does Between Work With Dates In SQL Server?
There's a trick with datetimes in databases - you almost never want an = comparison, because as you saw they also include a time component. Instead, you want to know if it falls inside a range that includes the entire day. Sql Server 2008 has a new date type that helps with this, but until you upgrade, do it like this:
WHERE (ChangingDate >= dateadd(dd,1, datediff(dd,0, getDate()))
AND ChangingDate < dateadd(dd,2, datediff(dd,0, getDate())))
You can do an equals comparison if you are certain that all the records have a 0-value (or other known value) for the time component in that column. What you don't want to do is truncate the column, because that means doing extra work per-record (slow) and will break your index (very slow).
select *
from MyTable
where DATEADD(dd, 0, DATEDIFF(dd, 0, ChangingDate)) = SELECT DATEADD(dd, 1, DATEDIFF(dd, 0, GETDATE()))
you may want to try something like
select * from table where columndate=GetDate() + 1
Sounds like you want the DATEPART function to find where the column date has the same year, month, day regardless of time of day:
SELECT * FROM Table
WHERE
DATEPART(Month, Date) = DATEPART(Month, #SomeDate)
AND DATEPART(Day, Date) = DATEPART(Day, #SomeDate)
AND DATEPART(Year, Date) = DATEPART(Year, #SomeDate)
Otherwise, you want to use DateAdd like the other posters.