Get only month and year in SQL Server - sql

I want to fetch only month and year from a date column in SQL Server.
Example: if today's date is 02/03/2019, then I want 0319.
Note: I want the result in same order (2 digit month and 2 digit year). Zero should not be removed from month.

As an alternative approach, you could go for:
RIGHT(REPLACE(CONVERT(varchar(8),DateColumn,3),'/',''),4)

You can create a number using:
select month(datecol) * 100 + (year(datecol) % 100)
Prepending the zeros requires a bit more work:
select right('0' + convert(varchar(255), month(datecol) * 100 + (year(datecol) % 100)), 4)
Or, you can use format():
select format(datecol, 'MMyy')

You can try this
substring(convert(nvarchar,#date,12),3,2) + left(convert(nvarchar,#date,12),2)
You can create an user defined function, and then apply to your column/s
create function udf_Getmonthyear(#date as date)
RETURNS nchar(4)
BEGIN
DECLARE #d_format nchar(6) = (select convert(nvarchar,#date,12))
RETURN (select SUBSTRING(#d_format,3,2) + left(#d_format,2))
end
go

Use function DATEPART in TSQL to get any part of a DateTime value. e.g:
DATEPART(yy,datecol) gives you 4 digit year part of a DateTime column (e.g: datecol), using the % (modulus) operator you can get 2 digit year DATEPART(yy,datecol)%100.
DATEPART(mm,datecol) gives you month part of the datecol field.
select Right('0'+cast(DATEPART(mm,datecol) as varchar(2)),2) +
Right('0'+cast(DATEPART(yy,datecol)%100 as varchar(2)),2) MonthYearPart
from MyTable
Regards

Related

Convert whole number to Month-Year

I am working in SQL Server, I have a column of numbers that represent the year and the month, such as:
YearandMonth
------------
202108
202109
202110
How do I convert this to an output like this?
YearandMonth
------------
Aug-2021
Sept-2021
Oct-2021
Thank you in advance
Steps:
Get the year and the month from the number.
Create a date from the year and the month.
Get the abbreviated month name from that date.
Concatenate month name and year.
The query:
select
format(datefromparts(yearanddate / 100, yearanddate % 100, 1), 'MMM', 'en-US') +
'-' +
cast(yearanddate / 100 as varchar(4))
from mytable;
select DATE_FORMAT(CONCAT(`yearandmonth`,'01'), '%b-%Y') as 'YearandMonth' from test_table;
by adding the 1st day of each month it provides the standard format so we can just use DATE_FORMAT() to get the result we need.
For SQL Server 2008 this should work fine. Untested, of course:
with myTable as (
select * from (values(202108),(202109),(202110))v(YearAndMonth)
)
select Left(DateName(month,Convert(date,Cast(YearAndMonth *100+1 as varchar(8)))),3) + '-' + Left(Cast(YearAndMonth as varchar(6)),4)
from myTable

Looking to replace the year in SQL Server

I am converting a date using CONVERT(varchar,DateOfBirth,101) for birthdates.
I want to show these dates with the current year, I've tried REPLACE but you can't use wildcards with it and when I use DATEPART, it doesn't format with the right digits for month and day. I also can't add years because they are wildly different birthdates. Thanks.
If you want to display the date as a string in 101 format for current year, one option uses a direct format():
format(DateOfBirth, 'MM/dd/2020')
You can compute the current date dynamically:
format(DateOfBirth, concat('MM/dd/', year(getdate())))
On the other hand, if you want your result as a date, then you could use datefromparts():
datefromparts(year(getdate()), month(DateOfBirth), day(DateOfBirth))
If it is a datevalue, you can use FORMAT function. If it is a character value, you can use RIGHT and REPLACE.
DECLARE #dateValue DATETIME = '05/12/1999'
DECLARE #dateCharValue VARCHAR(12) = '05/12/1999'
SELECT FORMAT(#dateValue, 'MM/dd/2020')
SELECT REPLACE(#dateCharValue, RIGHT(#dateCharValue,4),2020)
--Result
05/12/2020
This could helped you:
The code CONVERT(varchar(5),GETDATE(),1) return this 05/27 and then just add the year of the date
SELECT CONVERT(varchar(5),GETDATE(),1) + '/' + cast(year(getdate()) as varchar)
Or
SELECT CONVERT(varchar(5),GETDATE(),1) + '/' + convert(varchar,year(getdate()))
The result of both:
05/27/2020 --(This is my current date n.n )
This work but if you use a string something like your example DateOfBirth will be the variable and if this is a string (DateOfBirth = '5/27/1987') you need to convert the string DateOfBirth to Date:
SELECT CONVERT(varchar(5),convert(date,DateOfBirth),1) + '/' + cast(year(GETDATE()) as varchar)
Or
SELECT CONVERT(varchar(5),convert(date,DateOfBirth),1) + '/' + convert(varchar,year(GETDATE()))
The Result of Both :
05/27/2020

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

Two Digit date format in SQL

I have a table field AccID where I have to concatenate Name with Date like 'MyName-010415' in SQL query.
Date format is 01-04-2015 or 01/04/2015. But I want to display it like 010415.
For the date part, to get the format you want you, try this:
SELECT
RIGHT(REPLICATE('0', 2) + CAST(DATEPART(DD, accid) AS VARCHAR(2)), 2) +
RIGHT(REPLICATE('0', 2) + CAST(DATEPART(MM, accid) AS VARCHAR(2)), 2) +
RIGHT(DATEPART(YY, accid), 2) AS CustomFormat
FROM yourtablename
...
The DATEPART(DD, accid) will give you the day part and the same for mm and yy will give you the month and the year parts. Then I added the functions RIGHT(REPLICATE('0', 2) + CAST(... AS VARCHAR(2)), 2) to add the leading zero, instead of 1 it will be 01.
SQL Fiddle Demo
As #bernd-linde suggested, you can use this function to concatenate it with the name part like:
concat(Name, ....) AS ...
Also you can just SELECT or UPDATE depending on what you are looking for.
As in #bernd-linde's fiddle.
I am not sure which language you are using. Let take php as an example.
$AccID = $name.'-'.date('dmy');
OR before you save this data format the date before you insert the data in database.. or you can write a trigger on insert.
You need to use DATE_FORMAT to change format of your date and CONCAT to marge name with date.
Example:
SELECT CONCAT(name, '-', DATE_FORMAT(field,'%m%d%y'))
FROM tbl

Count with last 4 digits which represent Date

I have a question
Can we convert date 20-06-2011 (dd-mm-yyyy) into 0611 using sql (SQL server database) ?
And
Can we count ID below
keeping in mind last 4 digits which represent date (last 4 digits represent date in the form MMYY) so numbers with last 4 digits 0611 count should be 3
What would be the SQl Query for the count?
ID
AOB2340511
AOB4560511
AOB3500611
AOB4410611
AOB5120611
AOB1250411
EDIT: Corrected DATE data type option.
If your date fields are DATE data types you can do the following.
SELECT RIGHT('0' + CAST(DATEPART(MM, #TheDate) as VARCHAR), 2)
+ RIGHT(CAST(DATEPART(YY, #TheDate) as VARCHAR), 2)
If your date fields are stored as a string type, such as VARCHAR, NVARCHAR, etc, then try the following
select SUBSTRING(TheDate, 4, 2) + SUBSTRING(TheDate, 9, 2)
For the question about count, you can try this
SELECT RIGHT(ID, 4) AS TheDate, Count(*) AS TheCount
FROM MyTable
GROUP BY RIGHT(ID, 4)
If you need a query for the count that also shows the ID value, give this a try
SELECT ID, RIGHT(ID, 4) as MMYY,
COUNT(*) OVER (PARTITION BY RIGHT(ID, 4)) AS TheGroupCount
FROM MyTable
ORDER BY ID
This gives you "YYMM":
SELECT SUBSTRING(CONVERT(VARCHAR,getdate(),12),1,4)
To get the 2-digit month before the 2-digit year you need to do:
SELECT SUBSTRING(CONVERT(VARCHAR,getdate(),12),3,2) + SUBSTRING(CONVERT(VARCHAR,getdate(),12),1,2)
getdate() is just the current datestamp; substitute that with the date field you want to reformat.
CONVERT(...,12) gives you YYMMDD datestamp. See this helpful page for more magic numbers to use as the 3rd parameter: http://sql.dzone.com/news/custom-date-formatting-sql-ser
(BTW, using DATEPART(MM,getdate()) gives a 1-digit month not 2 digits, and DATEPART(YY,getdate()) gives a 4-digit year, not 2 digits. I.e. the DATEPART approach seems doomed)