In SQL Server Denali, a new string function called FORMAT() has been introduced. This function allows developers to convert values to a specified format and return them as a string. One of the key advantages of this function is that it is locale-aware, meaning it can format dates and numbers according to the specified locale. This can greatly simplify formatting tasks and help developers avoid writing unnecessary code.
Let’s take a look at some examples to understand how the FORMAT() function works:
Example 1: Location Aware FORMAT function with Date
DECLARE @d DATETIME = '01/01/2011'; SELECT FORMAT ( @d, 'd', 'en-US' ) AS US_Result; SELECT FORMAT ( @d, 'd', 'fr-FR' ) AS FR_Result; SELECT FORMAT ( @d, 'd', 'de-DE' ) AS DE_Result;
Example 2: Location Aware FORMAT function with Currency
DECLARE @d INT = 500; SELECT FORMAT ( @d, 'c', 'en-US' ) AS US_Result; SELECT FORMAT ( @d, 'c', 'fr-FR' ) AS FR_Result; SELECT FORMAT ( @d, 'c', 'de-DE' ) AS DE_Result;
Example 3: Various formats of Datetime
-- Day SELECT FORMAT ( GETDATE(), 'd', 'en-US' ) AS US_Result; SELECT FORMAT ( GETDATE(), 'dd', 'en-US' ) AS US_Result; SELECT FORMAT ( GETDATE(), 'ddd', 'en-US' ) AS US_Result; SELECT FORMAT ( GETDATE(), 'dddd', 'en-US' ) AS US_Result; -- Minutes SELECT FORMAT ( GETDATE(), 'm', 'en-US' ) AS US_Result; SELECT FORMAT ( GETDATE(), 'mm', 'en-US' ) AS US_Result; SELECT FORMAT ( GETDATE(), 'mmm', 'en-US' ) AS US_Result; SELECT FORMAT ( GETDATE(), 'mmmm', 'en-US' ) AS US_Result; -- Year SELECT FORMAT ( GETDATE(), 'y', 'en-US' ) AS US_Result; SELECT FORMAT ( GETDATE(), 'yy', 'en-US' ) AS US_Result; SELECT FORMAT ( GETDATE(), 'yyy', 'en-US' ) AS US_Result;
Example 4: Various formats of Currency
DECLARE @var INT = 50 SELECT FORMAT(@var,'c') AS Currency; SELECT FORMAT(@var,'c1') AS Currency; SELECT FORMAT(@var,'c2') AS Currency; SELECT FORMAT(@var,'c3') AS Currency;
Example 5: Various miscalculation formats
DECLARE @var INT = 50 SELECT FORMAT(@var,'p') AS Percentage; SELECT FORMAT(@var,'e') AS Scientific; SELECT FORMAT(@var,'x') AS Hexa; SELECT FORMAT(@var,'x4') AS Hexa1;
Example 6: Format returning results in various languages
SELECT FORMAT (GETDATE(), N'dddd MMMM dd, yyyy', 'en-US') AS English_Result; SELECT FORMAT (GETDATE(), N'dddd MMMM dd, yyyy', 'hi') AS Hindi_Result; SELECT FORMAT (GETDATE(), N'dddd MMMM dd, yyyy', 'gu') AS Gujarati_Result;
The FORMAT() function can also be used with table columns. Here is a quick example:
Example 7: Format returning results based on table column
SELECT ModifiedDate, FORMAT(ModifiedDate, N'dddd MMMM dd, yyyy','fr') Fr_ModifiedDate, UnitPrice, FORMAT(UnitPrice, 'c','fr') Fr_UnitPrice FROM Sales.SalesOrderDetail
As you can see, the FORMAT() function is a powerful tool that simplifies formatting tasks in SQL Server Denali. It has made life easier for developers by providing a convenient way to format dates, numbers, and currencies according to different locales.