Recently, I was developing a report in a legacy application. In that application we had used SQL Server 2005 and later on migrated to SQL Server 2012. The problem I came across while developing the report was I needed the ‘year’ in two digit format. Normally the year is in four digits like 2013 but it should be in two digits only like 13 to match with the saved data in the tables.
Given below are the two different methods.
Method 1 :
In this method, we will use TWO functions (RIGHT & YEAR) to achieve it.
--This script is compatible with SQL Server 2005 and above. DECLARE @datetime DATETIME SET @datetime = GETDATE() SELECT RIGHT(YEAR(@datetime),2) AS [Two digit year] --OUTPUT
Two digit year
————–
13
(1 row(s) affected)
Method 2 :
In the second method, we will use only ONE function (FORMAT) to achieve it.
--This script is compatible with SQL Server 2012 and above. DECLARE @datetime DATETIME SET @datetime = GETDATE() SELECT FORMAT(@datetime,'yy') AS [Two digit year] --OUTPUT
Two digit year
————–
13
(1 row(s) affected)
Leave a Reply