How do I check whether the input date's DAY is the last day of the given month in SQL? - sql

DECLARE #Date DATE = '2/28/2014'
I need to test whether the DAY in the DATE above is the LAST day of the month and it should work for all months in the year.
If it's true, then I need to return a true, if not, then false.
E.g.
SET #Date = '2/27/2014'
This should return FALSE.
SET #Date = '12/31/2014'
This should return TRUE.
I know you can manipulate this based on month but I'm just wondering whether there is an easy way to do it.

An easy way that works in almost any version of SQL Server is:
select (case when month(#date) <> month(dateadd(day, 1, #date))
then 'true' else 'false'
end)
That is, add a day and see if you are in the same month. This works for leap years, and Dec 31 and so on.

This will return 1 if its the last day of the month, and 0 otherwise
DATEDIFF(month,#date,#date+1)

As no one has given the 2012+ answer as an answer yet...
SELECT IIF(EOMONTH(#date) = #date, 'Yes','No')
As an aside you should use an unambiguous format for date literals such as ISO yyyy-mm-dd to avoid surprises when the code is executed under a login with different default options.

Related

SQL Server end of month

Suppose there is one date in int format 20191229, I want to find end of month and check if it's end of month is of 31 days or 30 days in SQL Server
You can try this from the reference. The given answer will not work for the integer data type but it will work in the varchar datatype date value. Storing Date values in integer is not a good idea, so as suggested by Larnu change the data type in either date or varchar.
SELECT
Day(EOMONTH(Cast('20191229' as Date))) end_of_month;
If you want the amount of days within a month, as you need the days as an integer, you should go for this. This is the most robust built, but also the more complex one, as to make sure the Integer value is processed correctly:
SELECT DATEPART(DAY,EOMONTH(CAST(CAST('20191229' AS NCHAR(8)) AS DATE))) AS Days
Result:
Days
31
If you want to add an IF evaluation to your selected date(s), you can do this by add an IIF-clause where it evaluates whether or not the end of month is 31 or not. If you want to use a columnname instead of the date, just substitute #Date with the columnname. I've just added the variable #Date instead of '20191229' to make it more illustrative/understandable. You can change the True/false descriptions to whatever you like in the query.
DECLARE #Date AS int
SET #Date = '20191229'
SELECT
IIF (
DATEPART(DAY,EOMONTH(CAST(CAST(#Date AS NCHAR(8)) AS DATE))) = '31'
,'True'
,'False'
) AS Days
Output:
Days
True

SQL IF statement for todays date

I'm trying to create a condition for my SQL, that shows a 1 if that row reflects today's day.
case when A.EntryDate = GETDATE() then '1' else '0' end as Today
That's accepted but it doesn't show anything but zeros. I've only worked with Access SQL and this one seems to dislike Date()
I've been looking all around for answers and I cannot seem to find one.
The GetDate() method return datetime. To compare today's date you need to convert datetime to date.
case when cast(A.EntryDate as date) = cast(getdate() as date) then 1 else 0 end

Function get the last day of month in sql

I need to get the last day of month with input of month and year. For example, with input 06/2016 it will return 30. I use SQL Server 2005. Thanks for any help.
Suppose your input is VARCHAR in the form of MM/YYYY.
Use RIGHT and LEFT to get the year and month respectively. Then use DATEFROMPARTS to generate the starting date. Next, use EOMONTH to get the last day of the month. Finally use DAY to extract the day part.
DECLARE #input VARCHAR(7) = '06/2016'
SELECT
DAY(
EOMONTH(
DATEFROMPARTS(CAST(RIGHT(#input,4) AS INT),CAST(LEFT(#input, 2) AS INT),1)
)
)
The above only works for SQL Server 2012+.
For SQL Server 2005, you can use DATEADD to generate the dates:
SELECT
DAY( -- Day part
DATEADD(DAY, -1, -- Last day of the month
DATEADD(MONTH, CAST(LEFT(#input, 2) AS INT), -- Start of next month
DATEADD(YEAR, CAST(RIGHT(#input, 4) AS INT) - 1900, 0) -- Start of the year
)
)
)
Reference:
Some Common Date Routines
You would do something like this:
select eomonth(getdate(), 0);
If you want it formatted as MM/YYYY then you'd do this:
select format(eomonth(getdate(), 0), 'MM/yyyy');
Pardon me for tossing-in a response that is not specific to "SQL Server," nor thence to "2005," but the generalized way to compute the answer that you seek is as follows:
Break down the input that you have, e.g. 06/2016, into two parts. Call 'em #MONTH and #YEAR. Define a third value, #DAY, equal to 1.
Typecast this into a date-value ... "June 1, 2016."
Now, using the date-handling functions that you're sure to have, "first add one month, then subtract one day."
One thing that you must be very careful of, when designing code like this, is to be certain(!) that your code for decoding 06/2016 works for every(!) value that actually occurs in that database, or that it can be relied upon to fail.
try this,
declare #input varchar(20)='06/2016'
set #input=#input+'/01'
declare #dtinput datetime=#input
select dateadd(day,-1,dateadd(month,datediff(month,0,#dtinput)+1,0))
--OR in sql server 2012
select eomonth(#dtinput)

SQL Start date is current day then end date is 1 month ago even if its not from the first to the last of the month

Ok I am trying to write a query that says get the current date and make it the start date. Then I want to go a month back from that current date for the EndDate. Is it possible to do this? Like if it was 9-15-2010 as the start date can I go a month back from that to 8-15-2010 or is this no possible....what would you do for like 9-20-2010 as the start date since every month has a different amount of days in it? Otherwise if this is not possible how else could I do this? The report will always be run on the 25th of the month so any ideas? I need to go from the 25th back a month....I can get some duplicate records between months if needed but less is obviously better
Right now I am using this:
DECLARE #StartDate DATETIME,
#EndDate DATETIME;
SET #StartDate = DATEADD(m,-1,GETDATE());
SET #EndDate = DATEADD(m, 1, #StartDate);
Does this work?
Also, how would I then say my AuditInsertTimestamp is between #Start adn #EndDate?
Currently I have this:
AND cvn.[AuditInsertTimestamp] BETWEEN #StartDate AND #EndDate ;
This is still giving me dates like 7-26-2010 though....
Thanks!
That should work. Did you try it?
If it doesn't work (and there are only 12 test cases to check if you don't trust the documentation) then you can re-build the date from the date parts.
Here's the problem. It should be like this:
cvn.[Subject] = 'Field Changed (Plate Type)'
AND (
cvn.[Note] LIKE 'Old Type: IRP%New Type: BASE PLATE%'
OR cvn.[Note] LIKE 'Old Type: Base Plate%New Type: IRP%'
)
AND cvn.AuditInsertTimestamp BETWEEN GETDATE() AND DATEADD(MONTH, -1, GETDATE())
AND takes precidence over OR, so you were picking up anything with Old Type:IRP or in the correct date range (with Old Type: Base Plate)
Based on your comment:
Well this is being used to select
records. So if I run it on the 25th I
need 30 days back then my field
AuditInsertTimestamp needs to be
between these 2 dates.
I think you need to do something like this:
SELECT * FROM Table
WHERE AuditInsertTimestamp BETWEEN GETDATE() AND DATEADD(MONTH, -1, GETDATE())

SQL Server: Get data for only the past year

I am writing a query in which I have to get the data for only the last year. What is the best way to do this?
SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'
The following adds -1 years to the current date:
SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.
At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.
SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))
Thanks to those above whose solutions helped me arrive at what I needed.
Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
Then if you want to restrict this query, you can add some other filter, but always searching in the last year.
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
The most readable, IMO:
SELECT * FROM TABLE WHERE Date >
DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))
Which:
Gets now's datetime GETDATE() = #8/27/2008 10:23am#
Converts to a string with format 101 CONVERT(varchar, #8/27/2008 10:23am#, 101) = '8/27/2007'
Converts to a datetime CONVERT(datetime, '8/27/2007') = #8/27/2008 12:00AM#
Subtracts 1 year DATEADD(yy, -1, #8/27/2008 12:00AM#) = #8/27/2007 12:00AM#
There's variants with DATEDIFF and DATEADD to get you midnight of today, but they tend to be rather obtuse (though slightly better on performance - not that you'd notice compared to the reads required to fetch the data).
Look up dateadd in BOL
dateadd(yy,-1,getdate())
GETDATE() returns current date and time.
If last year starts in midnight of current day last year (like in original example) you should use something like:
DECLARE #start datetime
SET #start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) -- getdatewithouttime() function doesn't exist in MS SQL -- you have to write one
SELECT column1, column2, ..., columnN FROM table WHERE date >= #start
I, like #D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. #samjudson's answer provides that. #D.E. White's answer returns results for the prior calendar year.
My query is a bit different in that it works for the prior year up to and including the current date:
SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))
For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017
For some reason none of the results above worked for me.
This selects the last 365 days.
SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
The other suggestions are good if you have "SQL only".
However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.
At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.
argument for DATEADD function :
DATEADD (*datepart* , *number* , *date* )
datepart can be: yy, qq, mm, dy, dd, wk, dw, hh, mi, ss, ms
number is an expression that can be resolved to an int that is added to a datepart of date
date is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value.
declare #iMonth int
declare #sYear varchar(4)
declare #sMonth varchar(2)
set #iMonth = 0
while #iMonth > -12
begin
set #sYear = year(DATEADD(month,#iMonth,GETDATE()))
set #sMonth = right('0'+cast(month(DATEADD(month,#iMonth,GETDATE())) as varchar(2)),2)
select #sYear + #sMonth
set #iMonth = #iMonth - 1
end
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):
SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())
Here's my version.
YEAR(NOW())- 1
Example:
YEAR(c.contractDate) = YEAR(NOW())- 1
For me this worked well
SELECT DATE_ADD(Now(),INTERVAL -2 YEAR);
If you are trying to calculate "rolling" days, you can simplify it by using:
Select ... FROM ... WHERE [DATE] > (GETDATE()-[# of Days])