How to dynamically update dates every year for a query? - sql

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

Related

Filter results after date SQL Server

I need to filter my query to extract the results between 25th of the previous month and 25th of the current month. The SP receives a date as parameter, which I am using to extract the current month.I tried to make some casting but I can't figure how to deal with the January month when the last month has a different year(there must be a more efficient way also)
#Date smalldatetime --received as parameter
select *
from mytable
where mytable.mydate between '25/'+cast(MONTH(#date)-1 as varchar(2))+'/'+cast(YEAR(#date) as varchar(4)) and '25/'+cast(MONTH(#date) as varchar(2))+'/'+cast(YEAR(#date) as varchar(4))
I would just do:
select t.*
from t
where mydate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 25)) and
mydate < datefromparts(year(getdate()), month(getdate()), 25)
I would use datefromparts() rather than trying to construct a date string for this purpose.
You don't need to do any casting. SQL Server's datetime functions are quite versatile. Try this:
SELECT *
FROM mytable
WHERE mytable.mydate BETWEEN DATEADD(DAY, 25, DATEADD(MONTH, DATEDIFF(MONTH, 0, #Date) - 1, 0)) AND DATEADD(DAY, 25, DATEADD(MONTH, DATEDIFF(MONTH, 0, #Date), 0))

Sql query for selecting entries with today's date

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

how to get records of previous day using tsql?

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)

composing a SQL query with a date offset

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.

Get the records of last month in SQL server

I want to get the records of last month based on my db table [member] field "date_created".
What's the sql to do this?
For clarification,
last month - 1/8/2009 to 31/8/2009
If today is 3/1/2010, I'll need to get the records of 1/12/2009 to 31/12/2009.
All the existing (working) answers have one of two problems:
They will ignore indices on the column being searched
The will (potentially) select data that is not intended, silently corrupting your results.
1. Ignored Indices:
For the most part, when a column being searched has a function called on it (including implicitly, like for CAST), the optimizer must ignore indices on the column and search through every record. Here's a quick example:
We're dealing with timestamps, and most RDBMSs tend to store this information as an increasing value of some sort, usually a long or BIGINTEGER count of milli-/nanoseconds. The current time thus looks/is stored like this:
1402401635000000 -- 2014-06-10 12:00:35.000000 GMT
You don't see the 'Year' value ('2014') in there, do you? In fact, there's a fair bit of complicated math to translate back and forth. So if you call any of the extraction/date part functions on the searched column, the server has to perform all that math just to figure out if you can include it in the results. On small tables this isn't an issue, but as the percentage of rows selected decreases this becomes a larger and larger drain. Then in this case, you're doing it a second time for asking about MONTH... well, you get the picture.
2. Unintended data:
Depending on the particular version of SQL Server, and column datatypes, using BETWEEN (or similar inclusive upper-bound ranges: <=) can result in the wrong data being selected. Essentially, you potentially end up including data from midnight of the "next" day, or excluding some portion of the "current" day's records.
What you should be doing:
So we need a way that's safe for our data, and will use indices (if viable). The correct way is then of the form:
WHERE date_created >= #startOfPreviousMonth AND date_created < #startOfCurrentMonth
Given that there's only one month, #startOfPreviousMonth can be easily substituted for/derived by:
DATEADD(month, -1, #startOfCurrentMonth)
If you need to derive the start-of-current-month in the server, you can do it via the following:
DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)
A quick word of explanation here. The initial DATEDIFF(...) will get the difference between the start of the current era (0001-01-01 - AD, CE, whatever), essentially returning a large integer. This is the count of months to the start of the current month. We then add this number to the start of the era, which is at the start of the given month.
So your full script could/should look similar to the following:
DECLARE #startOfCurrentMonth DATETIME
SET #startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)
SELECT *
FROM Member
WHERE date_created >= DATEADD(month, -1, #startOfCurrentMonth)
AND date_created < #startOfCurrentMonth
All date operations are thus only performed once, on one value; the optimizer is free to use indices, and no incorrect data will be included.
SELECT *
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, date_created) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
You need to check the month and year.
Add the options which have been provided so far won't use your indexes at all.
Something like this will do the trick, and make use of an index on the table (if one exists).
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = dateadd(mm, -1, getdate())
SET #StartDate = dateadd(dd, datepart(dd, getdate())*-1, #StartDate)
SET #EndDate = dateadd(mm, 1, #StartDate)
SELECT *
FROM Member
WHERE date_created BETWEEN #StartDate AND #EndDate
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = DATEADD(mm, DATEDIFF(mm,0,getdate())-1, 0)
SET #EndDate = DATEADD(mm, 1, #StartDate)
SELECT *
FROM Member
WHERE date_created BETWEEN #StartDate AND #EndDate
An upgrade to mrdenny's solution, this way you get exactly last month from YYYY-MM-01
Last month consider as till last day of the month.
31/01/2016 here last day of the month would be 31 Jan. which is not similar to last 30 days.
SELECT CONVERT(DATE, DATEADD(DAY,-DAY(GETDATE()),GETDATE()))
One way to do it is using the DATEPART function:
select field1, field2, fieldN from TABLE where DATEPART(month, date_created) = 4
and DATEPART(year, date_created) = 2009
will return all dates in april. For last month (ie, previous to current month) you can use GETDATE and DATEADD as well:
select field1, field2, fieldN from TABLE where DATEPART(month, date_created)
= (DATEPART(month, GETDATE()) - 1) and
DATEPART(year, date_created) = DATEPART(year, DATEADD(m, -1, GETDATE()))
declare #PrevMonth as nvarchar(256)
SELECT #PrevMonth = DateName( month,DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)) +
'-' + substring(DateName( Year, getDate() ) ,3,4)
SQL query to get record of the present month only
SELECT * FROM CUSTOMER
WHERE MONTH(DATE) = MONTH(CURRENT_TIMESTAMP) AND YEAR(DATE) = YEAR(CURRENT_TIMESTAMP);
SELECT * FROM Member WHERE month(date_created) = month(NOW() - INTERVAL 1 MONTH);
select * from [member] where DatePart("m", date_created) = DatePart("m", DateAdd("m", -1, getdate())) AND DatePart("yyyy", date_created) = DatePart("yyyy", DateAdd("m", -1, getdate()))
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)
SET #EndDate = dateadd(dd, -1, DATEADD(mm, 1, #StartDate))
SELECT * FROM Member WHERE date_created BETWEEN #StartDate AND #EndDate
and another upgrade to mrdenny's solution.
It gives the exact last day of the previous month as well.
WHERE
date_created >= DATEADD(MONTH, DATEDIFF(MONTH, 31, CURRENT_TIMESTAMP), 0)
AND date_created < DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0)
I'm from Oracle env and I would do it like this in Oracle:
select * from table
where trunc(somedatefield, 'MONTH') =
trunc(sysdate -INTERVAL '0-1' YEAR TO MONTH, 'MONTH')
Idea: I'm running a scheduled report of previous month (from day 1 to the last day of the month, not windowed). This could be index unfriendly, but Oracle has fast date handling anyways.
Is there a similar simple and short way in MS SQL? The answer comparing year and month separately seems silly to Oracle folks.
You can get the last month records with this query
SELECT * FROM dbo.member d
WHERE CONVERT(DATE, date_created,101)>=CONVERT(DATE,DATEADD(m, datediff(m, 0, current_timestamp)-1, 0))
and CONVERT(DATE, date_created,101) < CONVERT(DATE, DATEADD(m, datediff(m, 0, current_timestamp)-1, 0),101)
I don't think the accepted solution is very index friendly
I use the following lines instead
select * from dbtable where the_date >= convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120) and the_date <= dateadd(ms, -3, convert(varchar(10),DATEADD(m, 0, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120));
Or simply (this is the best).
select * from dbtable where the_date >= convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120) and the_date < SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
Some help
-- Get the first of last month
SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
-- Get the first of current month
SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
--Get the last of last month except the last 3milli seconds. (3miliseconds being used as SQL express otherwise round it up to the full second (SERIUSLY MS)
SELECT dateadd(ms, -3, convert(varchar(10),DATEADD(m, 0, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120));
Here is what I did so I could put it in a view:
ALTER view [dbo].[MyView] as
with justdate as (
select getdate() as rightnow
)
, inputs as (
select dateadd(day, 1, EOMONTH(jd.rightnow, -2)) as FirstOfLastMonth
,dateadd(day, 1, EOMONTH(jd.rightnow, -1)) as FirstOfThisMonth
from justdate jd
)
SELECT TOP 10000
[SomeColumn]
,[CreatedTime]
from inputs i
join [dbo].[SomeTable]
on createdtime >= i.FirstOfLastMonth
and createdtime < i.FirstOfThisMonth
order by createdtime
;
Note that I intentionally ran getdate() once.
In Sql server for last one month:
select * from tablename
where order_date > DateAdd(WEEK, -1, GETDATE()+1) and order_date<=GETDATE()
DECLARE #curDate INT = datepart( Month,GETDATE())
IF (#curDate = 1)
BEGIN
select * from Featured_Deal
where datepart( Month,Created_Date)=12 AND datepart(Year,Created_Date) = (datepart(Year,GETDATE())-1)
END
ELSE
BEGIN
select * from Featured_Deal
where datepart( Month,Created_Date)=(datepart( Month,GETDATE())-1) AND datepart(Year,Created_Date) = datepart(Year,GETDATE())
END
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = dateadd(mm, -1, getdate())
SET #StartDate = dateadd(dd, datepart(dd, getdate())*-1, #StartDate)
SET #EndDate = dateadd(mm, 1, #StartDate)
set #StartDate = DATEADD(dd, 1 , #StartDate)
The way I fixed similar issue was by adding Month to my SELECT portion
Month DATEADD(day,Created_Date,'1971/12/31') As Month
and than I added WHERE statement
Month DATEADD(day,Created_Date,'1971/12/31') = month(getdate())-1
If you are looking for last month so try this,
SELECT
FROM #emp
WHERE DATEDIFF(MONTH,CREATEDDATE,GETDATE()) = 1
If you are looking for last month so try this,
SELECT
FROM #emp
WHERE DATEDIFF(day,CREATEDDATE,GETDATE()) between 1 and 30
A simple query which works for me is:
select * from table where DATEADD(month, 1,DATEFIELD) >= getdate()
If you are looking for previous month data:
date(date_created)>=date_sub(date_format(curdate(),"%Y-%m-01"),interval 1 month) and
date(date_created)<=date_sub(date_format(curdate(),'%Y-%m-01'),interval 1 day)
This will also work when the year changes. It will also work on MySQL.