Find Birthday in upcoming month - sql

I Need help in finding upcoming birthday in a month.
My Data is something like below , Both data types are nvarchar
Could anyone help me with the sql query please? how to set the DOB column into a date format and then find the birthday with month as 11 and date as 24.
Thanks in advance

Assuming SQL Server, you can use month() to extract the month from a date, for example getdate(), which is the current point in time. With left() you can extract the first characters of a string. That leads to something like:
SELECT [Name],
[Dob(mmdd)]
FROM elbat
WHERE month(getdate()) = left([Dob(mmdd)], 2);

In Microsoft SQL Server you can Create a date using the DATEFROMPARTS(int year, int month, int day) function. To get your month and day you would have to get the 2 parts of the string, the first 2 characters for month and the third and fourth characters as the day, you can use the SUBSTRING function for this. Then take each pair of characters for month and day and cast to int and use them in the DATEFROMPARTS function.
Then you want to see if your newly created date is BETWEEN today AND one month from today. So you could do something like this:
SELECT *
FROM SomeTable
WHERE
DATEFROMPARTS(YEAR(GETDATE()), CAST(SUBSTRING([Dob(mmdd)], 1, 2) as INT), CAST(SUBSTRING([Dob(mmdd)], 3, 2) as INT))
BETWEEN
DATEADD(DAY, -1, GETDATE()) AND DATEADD(MONTH, 1, GETDATE())
Note: this assumes [Dob(mmdd)] is always 4 characters.

You don't need the DOB in a date format. I am unclear what "upcoming" month means, but I suspect that it means a calendar month. If the current month, then:
where month(getdate()) = cast(left(dob, 2) as int)
If the next month, then:
where month(dateadd(month, 1, getdate())) = cast(left(dob, 2) as int)

Thanks, Everyone for the help.. I got this working,. both works perfect
select [USER_ID],[EMP_FULL_NM],[Birthday_Date] from [dbo].[COE]
where month(getdate())=left([Birthday_Date],2)
select [USER_ID],[JOINING_DT],[EMP_FULL_NM] from [dbo].[COE]
where SUBSTRING(CONVERT(VARCHAR(10), [JOINING_DT], 101),1,2) = month(getdate())

Related

How to get start and end of month in numeric type for SQL where clause

I want to run a query monthly to look for records from the previous month. The where clause will be greater or equal to the 1st day of the month and less or equal to the last day. The difficultly I am having is the dates are stored as numbers in a column with a numeric data type. The format being used is yyyymmdd. We are currently manually changing the where clause, so e.g. show me any records with dates >=20201001 to <=20201031, but we need to automate this process. I have tried a few ways to try and solve this but need some guidance.
So far I've tried:
select concat( CONCAT(cast((Year(DATEADD(month, -1, getdate()))) as numeric),cast((Month(DATEADD(month, -1, getdate()))) as numeric)),'01')
Returns error message operand data type numeric is invalid for concat operator. Works in separate query window returning format yyyymmdd.
SELECT DATEADD(mm, DATEDIFF(mm, 0, (DATEADD(month, -1, getdate()))), 0)
Returns error message arithmetic overflow error converting expression to data type date time. Works partly in separate query window but returns yyyy-mm-dd hh:mi:ss:ms
Any help would be greatly appreciated.
Thanks
The real solution is fix the design; don't store dates in a datatype other than a date and time data type.
What you can do, however, is convert the value of GETDATE() to a numerical value of the same format:
SELECT ...
FROM ...
WHERE NumericalDate >= CONVERT(varchar(8),DATEADD(DAY, 1, EOMONTH(GETDATE(),-1)),112)
AND NumericalDate < CONVERT(varchar(8),DATEADD(DAY, 1, EOMONTH(GETDATE())),112)
For today, this would return rows where NumericalDate is in November 2020 (specifically on or after 20201101 and before but not on 20201201).
Note, I don't "bother" to CAST/CONVERT the varchar to a Numerical data type, as it'll be implicit cast due to data type precedence.
You can use artihmetics like so:
where dates >= year(getdate()) * 10000 + month(getdate()) * 100 + 1
and dates < year(dateadd(month, 1, getdate())) * 10000 + month(dateadd(month, 1, getdate())) * 100 + 1
Compare the month and forget the days.
BETWEEN 20201000 and 20201099 finds the same rows as your example >=20201001 to <=20201031
That means that you do not have to figure out how many days are in the month.

Hardcode a specific day in data time while pulling the data - SQL

Actually I have different date in SQL table when I pull those via SQL query, day of datetime field should have fixed day.
Example: (DD-MM-YYYY) day should be "7" > (7-MM-YYYY)
10-08-2007 > 07-08-2007
27-12-2013 > 07-12-2013
01-03-2017 > 07-03-2017
Can someone help me on this. Thanks in Advance.
Find the difference between 7 and the day of the original date and add that to the original date:
SELECT DATEADD(DAY, 7 - DAY(OriginalDate), OriginalDate)
Use DATEPART to take out the month and year parts. Cast those into varchar and concatenate with 07.
Query
select '07-' +
cast(DATEPART(mm, [date_column]) as varchar(2)) + '-' +
cast(DATEPART(yyyy, [date_column]) as varchar(4))
from your_table_name;
Assuming You might have to change the day number example
DECLARE #dayNum char(2)
SELECT #dayNum = '07'
select #dayNum + Right(convert(char(10),getdate(),105),8)
If that is not the case You could do this
select '07'+ Right(convert(char(10),'10-08-2007',105),8)
I'd go this way:
SELECT CONVERT(DATE,CONVERT(VARCHAR(6),GETDATE(),112)+'25',112);
CONVERT with format 112 will return the date as unseparated ISO (today we would get 20170407). Convert this to VARCHAR(6) will implicitly cut away the day's part (201704).
Now we add a day and use again CONVERT with 112, but now with DATE as target type.
One thing to keep in mind: The day you add must be two-digit. You can achieve this with
DECLARE #int INT=7;
SELECT REPLACE(STR(#int,2),' ','0');
Use DATEFROMPARTS: Updated ONLY works from 2012 - OP has tagged SQL-Server 2008
select DATEFROMPARTS ( year('10-08-2007'), month('10-08-2007'), 7 )
Assuming that your field is of datetime datatype and your fixed day is of integer type.
select datetimecolumn+(yourparamfixedday-datepart(dd,datetimecolumn))

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)

Format varchar type and convert it to date variable

I have a varchar value in this format “YYYYMM-LL” where: YYYY is four digit year; MM is two digit month.LL is two digit length of reporting period. This is the number of whole months included in the calculations (from first to last day of each month).
My questions is how I could use this varchar value to decide two variables:#First_Date and #Last_Date.
Example: 201409-06
This scenario is for the six months ending in September of 2014.
The range of calendar dates in this scenario is 04/01/2014 through 09/30/2014.
So how could I use t-sql to find this two dates #First_Date : 04/01/2014 and #Last_Date: 09/30/2014.
Any help would be really appreciated!
You can do something like this:
select #firstdate = dateadd(month, 1 - cast(right('201409-06', 2) as int),
convert(date, left('201409-06', 6) + '01')
),
#lastdate = dateadd(day, -1,
dateadd(month, 1,
convert(date, left('201409-06', 6) + '01')
)
)
This parses the string to do the date arithmetic that you want. SQL Server recognizes a string in the form of "YYYYMMDD" as a date, regardless of internationalization settings.
And a SQL Fiddle.

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