SQL Server 2012 Format Function

SQL Server 2012 has introduced many new functions. We will see some of them in this series.

One of the most common challenge for a SQL Developer is to format a date. In earlier versions, we had to use the CONVERT function with format style number. In SQL Server 2012, we have a new function named FORMAT which can format dates in various formats.

The following codes are self explanatory

declare @d datetime
set @d='20110119 12:33:22'

--Format date in dd-mm-yyyy format
select format(@d,'dd-MM-yyyy') as [dd_mm_yyyy]

--Format date in mm/dd/yyyy format
select format(@d,'MM/dd/yyyy') as [mm/dd/yyyy]

--Format date in mmm-yyyy format
select format(@d,'MMM-yyyy') as [MMM-yyyy]

--Format date in MMM dd,yyyy format
select format(@d,'MMM dd,yyyy') as [MMM dd,yyyy]

--Format date in HH:MM:SS format
select format(@d,'HH:mm:ss') as [HH:mm:ss]

--Format date in long format
select format(@d,'dddd, dd MMMM yyyy') as [long format]


All you have to do is to give the format in a specific way you want. Here’s the output

sql-2012-format


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

No comments: