Formatting dates and times has aways presented a few challenges in T-SQL. Seems most other languages support a FORMAT command.
Well, time to rejoice because (finally) MS SQL 2012 (and more recent) now supports the FORMAT function. One little "gotcha" is you need .Net Framework because it leverages CLR. Which also means that it cannot be remoted (which is nothing new for CLR runtime).
So, with that out of the way, and for a large majority of T-SQL requirements, it is like any other system function. Probably easiest to show you :)
First, some dummy data. Create an order table with date and price columns, then populate :-
The structre of the command is FORMAT ( value, format_str , culture ] ) and can be found at MSDN Now, [culture] is optional and I tend to leave it out so it can default to the way my server / systems are set up.
So, with our Order Table, let us experiment with our new command...
SELECT Customer, FORMAT(Order_Date,'yyyy MMM dd'), Order_PriceFROM EE_tbl_Orders-- Results-- Fred 2015 Aug 20 1234.5678
Makes it a LOT easier, especially if you are familiar with format codes from other languages. Basically, the format characters in the format_str is one of d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" and known as a format specifier. Any other character will show as is. If you want the result to contain one of those characters, you have to use the backslash "\" as an escape character (including for its own use where you want a backslash).
For example date delimiters... Including a hyphen just needs to be there, but a forward slash needs to be 'escaped' with a backslash first :
There is now a significant function (finally) available to us T-SQL programmers. We can get pretty sophisticated such as FORMAT(Order_Date,'"Ordered On "yyyy-MMM-dd') including a double quoted string. But that is probably another Article.
Well, hope I have been able to share something new in T-SQL 2012. Please vote "Good Article" below.