How to calculate a date after 1 month currentDate - sql

How can I calculate a date after a month of current date.
Example if I have 19/04/2012 I want to get 19/05/2012. Is there any function on sql that allows doing this?
I need to do the same for a year also like 19/04/2012 and set 19/04/2013
Cheers

You can use
DATEADD (datepart , number , date )
as specified here
Examples (thanks to DarrenDavis)
for month:
select dateadd(m, 1, getdate())
for year:
select dateadd(YY, 1, getdate())

Use the dateadd() function
SELECT dateadd(mm, 1, '19-Apr-2012')

To add 1 month to the current date:
SELECT DATEADD(m, 1, GETDATE())
To add 1 year to the current date:
SELECT DATEADD(YY, 1, GETDATE())
For additional arguments see:
http://msdn.microsoft.com/en-us/library/ms186819.aspx

Something like this should do the job
SELECT DATEADD(month, 1, '2012-04-19')
for a year
SELECT DATEADD(year, 1, '2012-04-19')
http://msdn.microsoft.com/en-us/library/ms186819.aspx

You can use DateAdd:
select dateadd(m, 1, getdate())
select dateadd(yy, 1, getdate())
search online for other period indicators such as hour, minute, etc!

You can use this query for 1 month ahead date . This query works fine in oracle.
select add_months(trunc(sysdate),1) from dual;
For 1 year ahead date use this query
select add_months(trunc(sysdate),12) from dual;

Related

SQL CASE rolling date difference

How would I pull the annual rolling date difference within a case statement? Or, if there's a better method that would work. When the NXT Anniversary Date month is after the current month, then I need the date to roll to the next year. I need to see the next anniversary dates that would be coming up in 2022.
For example:
Below is the code I was using, which works great for the current year.
Declare #prevbiz as Date set #prevbiz = DateAdd(day,Case (Datepart(Weekday,Cast(GetDate() as Date)))
When 2 then -3
Else -1
End, Cast(GetDate() as Date));
DECLARE #prev12MONTHS AS DATE set #prev12MONTHS = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 12, DAY(#enddate)-1)
SELECT
ANNUALREVIEWDATE
, 'NXT Anniversary Date' = CASE WHEN DATEADD(yy, DATEDIFF(yy, ANNUALREVIEWDATE, #prevbiz), ANNUALREVIEWDATE) <= #prev12MONTHS
THEN DATEADD(yy, DATEDIFF(yy, ANNUALREVIEWDATE, #prevbiz) -1, ANNUALREVIEWDATE)
ELSE DATEADD(yy, DATEDIFF(yy, ANNUALREVIEWDATE, #prevbiz), ANNUALREVIEWDATE)
END
FROM [table]
I believe you're just looking to decide whether the anniversary has already passed and should then be advanced to next year.
datefromparts(
year(getdate()) +
case when datefromparts(2000, month(getdate()), day(getdate()))
>= datefromparts(2000, month(X), day(X))
then 1 else 0 end,
month(getdate()),
day(getdate())
)
You could also just compare month and day parts individually. Year 2000 is just an arbitrary year that happens to have a leap day.
Based on my findings on your question, this maybe could help you.
with dates(annualAnniversary) as (
select DateAdd(month,6,DateAdd(year,-5,cast(GetDate() as date)))
union
select DateAdd(month,3,DateAdd(year,-4,cast(GetDate() as date)))
union
select DateAdd(month,3,DateAdd(year,-1,cast(GetDate() as date)))
union
select DateAdd(month,5,DateAdd(year,-2,cast(GetDate() as date)))
union
select DateAdd(month,2,DateAdd(year,-1,cast(GetDate() as date)))
union
select DateAdd(month,8,DateAdd(year,-3,cast(GetDate() as date)))
union
select DateAdd(month,0,DateAdd(year,0,cast(GetDate() as date)))
)
select annualAnniversary,
DateAdd(year,DATEDIFF(year,annualAnniversary, cast(GetDate() as date)),annualAnniversary) as needsToShow
from dates
for excluding rows those not meet their own annual Anniversary, You can add this to the above code:
where DATEDIFF(year,annualAnniversary, cast(GetDate() as date))>0
Output with raw data:

date format : get the last and the first day in the month-sql-DB2

how i can write the following date with date function.. IN DB2
L2.FOM >= '2015-08-01' // the first day of the current Month
L2.TOM <= '2015-08-31' // the last day of the current Month
i tried this but it doesnot work
L2.FOM=DATEADD(month,DATEDIFF(month,0,CURRENT DATE), 0) //for the first day of the month
last date
DECLARE #date DATETIME = '12/1/2011';
SELECT EOMONTH ( #date ) AS Result;
GO
first date - is known to start from 1.
but here it is for name sake.
SELECT DATEADD(month, DATEDIFF(month, 0, #date), 0) AS StartOfMonth
Your code looks like SQL Server.
In that database, I would suggest using eomonth():
select eomonth(getdate()) as last_date_of_month,
dateadd(day, 1, eomonth(getdate(), -1)) as first_date_of_month
For the first date of the month, I also often use:
datefromparts(year(getdate()), month(getdate()), 1)

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))

Specific day of current month and year

I have problem with return of specific day of current month and year. I need for example 15th day. Until now I used in FB/IB existing function:
IB_EncodeDate(EXTRACT(YEAR FROM Current_Date),EXTRACT(Month FROM Current_Date),15)
Does it exist a simply way to convert this for MSSQL database?
edit. I need output in OLE format (41,348 by example) to compare date with another date. I compare date from database with 15th day of current month.
For the 15th day of current month:
SELECT DATEADD(DAY, 14, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0));
To get the silly OLE representation based on this "magic" date, 1899-12-30:
SELECT DATEDIFF(DAY, -2, DATEADD(DAY, 14,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)));
Answer (on March 11th, when I updated this answer for the changed requirement):
-----
41348
So, you have a date, and want to return the 15th day of the same month?. Well, assuming SQL Server 2008, you could do this:
SELECT CONVERT(DATE,CONVERT(VARCHAR(6),GETDATE(),112)+'15',112)
For Previous versions of SQL Server:
SELECT CONVERT(DATETIME,CONVERT(VARCHAR(6),GETDATE(),112)+'15',112)
This seems like a quick answer.
declare #OLEDate int
declare #currentDate as datetime
set #currentDate = DATEADD(DAY, 14, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
set #OLEDate = convert(float, #currentdate)
-- PRINT #OLEDate
based on Aaron Bertrand's answer and your need for the integer conversion
To get 10th day of current day
declare #cur_month int,#cur_yr int,#tenth_dt date
set #cur_month=month(getdate())
set #cur_yr=YEAR(getdate())
set #tenth_dt=convert(date,'10/'+convert(varchar(5),#cur_month)+'/'+convert(varchar(5),#cur_yr),103)
select #tenth_dt
Not sure if you after Day or Date. This gives both dayOfWeek and specificDate for any culture
declare #myDay int = 15
select convert(date,myday) specificDate, datename(dw,myday) dayOfWeek
from (
select convert(varchar(6),getdate(),112) + convert(varchar, #myDay) myday
) x
Fiddle Demo Here
| SPECIFICDATE | DAYOFWEEK |
----------------------------
| 2013-02-15 | Friday |
Current_Date in SQL Server would be getdate().
To get the 15th day in OLE Automation format, try:
select datediff(day, '18991230', dateadd(day, -day(getdate()) + 15, getdate()))
A bit more straightforward approach:
CAST(FORMAT(GETDATE(), 'yyyy-MM-15') AS DateTime)

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.