SQL Server finding end date of the month - month range - sql

In my SQL Server procedure, I have one input parameter like created_date.
Based on that created date I have to find out first and last date of the month.
For example,
If created_date is 12-08-2016,
start_date should be '01-08-2016'
end_date should be '31-08-2016'
If Created_date is 15-06-2016
start_date should be '01-06-2016 00:00:00'
end_date should be '30-06-2016 23:59:59'

Since your input is in DD-MM-YYYY format, so it is need to covert first as MM-DD-YYYY then only it is easy to find the first and last day of the month.
The below query will accept the input and return the result in your expected format:
DECLARE #datevalue AS VARCHAR(20) = '15-06-2016'; --12-08-2016';
SELECT CONVERT(VARCHAR(10), DATEADD(M, DATEDIFF(M, 0, CONVERT(DATETIME, #datevalue, 105)), 0), 105) [start_date],
CONVERT(VARCHAR(10), DATEADD(D, -1, DATEADD(M, DATEDIFF(m, 0, CONVERT(DATETIME, #datevalue, 105)) + 1, 0)), 105) [end_date]
Output:
start_date end_date
----------------------
01-06-2016 30-06-2016

select
DATEADD(Month, DATEDIFF(Month, 0, GETDATE()), 0) as monthfirstdate,
CAST(EOMONTH(GETDATE()) as DATETIME) as monthlastdate
EOMONTH works from SQL server 2012

Related

Get data from last month in SQL Server

I checked Get the records of last month in SQL server and it did not work!
I try to get the records of last month based on my database table and column issue_date.
What's the SQL query to do this?
For clarification, today (27-April-18) I want to get all records from March-18.
I have the issue_date in the format that I convert to date but below code gives me all records from 01-March-2018 to and including today.
DATEPART(month, CONVERT (VARCHAR(11),DATEADD(day,wo_header.issue_date,`1971/12/31`),106)) = DATEPART(month, DATEADD(month, -1, getdate()))
To get firstDay and lastDay of previous month
DECLARE #FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -(DAY(DATEADD(m, -1, GETDATE() - 2))), DATEADD(m, -1, GETDATE() - 1))),
#LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -(DAY(GETDATE())), GETDATE()))
SELECT #FirstDayOfLastMonth, #LastDayOfLastMonth
Your required Query
SELECT *
FROM TABLE
WHERE CAST(issue_date AS DATE) BETWEEN CONVERT(DATE, DATEADD(d, -(DAY(DATEADD(m, -1, GETDATE() - 2))), DATEADD(m, -1, GETDATE() - 1))) AND CONVERT(DATE, DATEADD(d, -(DAY(GETDATE())), GETDATE()))
Perhaps the easiest method is eomonth(). If there is no time component on issuedate:
where issuedate > eomonth(getdate(), -2) and
issuedate <= eomonth(getdate(), -1)
If there is a time component:
where issuedate >= dateadd(day, 1, cast(eomonth(getdate(), -2) as date)) and
issuedate < dateadd(day, 1, cast(eomonth(getdate(), -1) as date))
Without eomonth, I would do:
where issuedate < cast(dateadd(day, 1 - day(getdate()), getdate()) as date) and
issuedate >= dateadd(month, -1, cast(dateadd(day, 1 - day(getdate()), getdate()) as date))
The code I figured out is not pretty but it works. It first adds extra column with the month number to the SELECT portion of my code:
Month(CONVERT (VARCHAR(11),DATEADD(day,wo_header.closing_date,'1971/12/31'),106)) As Month
And than is used for WHERE statement:
Month(CONVERT (VARCHAR(11),DATEADD(day,wo_header.closing_date,'1971/12/31'),106)) = month(getdate())-1
So for anyone like me working in SQL report kind-of environment it should work.

Only dates from current week

I use the following Query to display the entries in my tables where the date is located in the current week. I need to change it to only show from current date to end of the week, not the hole week.
SET DATEFIRST 1
SELECT distinct Initials
FROM Scheme
WHERE CONVERT(datetime, Dato, 105) >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND convert(datetime, Dato, 105) < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
AND RoomId = ? AND Initials IS NOT NULL
A bit different, but more effective method:
SELECT distinct Initials
FROM Scheme
WHERE Dato >= cast(current_timestamp as date) -- currentdate
AND Dato < dateadd(d, datediff(d, -7, current_timestamp)/7*7, 0)--end of week
AND RoomId = ? AND Initials IS NOT NULL
I assume Dato is defined as a date or datetime. Otherwise you may encounter some performance issues and this will not work.
dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
This means: add 1-datepart(dw, getdate()) days to current date.
This means 1-datepart(dw, getdate()): go to starting date of current week.
But you need just current date CONVERT(date,getdate()).
Just change your code to:
SET DATEFIRST 1
SELECT distinct Initials
FROM Scheme
WHERE CONVERT(datetime, Dato, 105) >= CONVERT(date,getdate())
AND convert(datetime, Dato, 105) < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
AND RoomId = ? AND Initials IS NOT NULL

How to get 00:00:00 in datetime, for First of Month?

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

How to get the last month data and month to date data

Need help in writing the query to get the last month data as well as month to date data.
If today's date is Mar 23 2011, I need to retrieve the data from last month and the data till todays date(means Mar 23 2011).
If date is Apr 3 2011, data should consists of March month data and the data till Apr 3rd 2011.
Thanks,
Shahsra
Today including time info : getdate()
Today without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 0)
Tomorrow without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Beginning of current month : DATEADD(month, datediff(month, 0, getdate()), 0)
Beginning of last month : DATEADD(month, datediff(month, 0, getdate())-1, 0)
so most likely
WHERE dateColumn >= DATEADD(month, datediff(month, 0, getdate())-1, 0)
AND dateColumn < DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Step back one month, subtract the number of days to the current date, and add one day.
WHERE
DateField <= GetDate() AND
DateField >= DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)
To remove the time quickly, you can use this
Cast( Floor( Cast( GETDATE() AS FLOAT ) ) AS DATETIME )
So the second part would be (without time)
DateField >= Cast( Floor( Cast( (DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)) AS FLOAT ) ) AS DATETIME )
Select Column1, Column2 From Table1
Where DateColumn <= GetDate() AND
DateColumn >= DATEADD(dd, - (DAY(DATEADD(mm, 1, GetDate())) - 1), DATEADD(mm, - 1, GetDate()))
Edit: +1 to Russel Steen. I was posting mine before I knew he had posted.
Very helpful page
declare #d datetime = '2011-04-03';
declare #startDate datetime;
select #startDate =
CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,#d),113),8) AS datetime);
select #startDate;

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