I am unrelenting in my creation of short articles or tidbits on Transaction SQL date/time functions.
Most, if not all, modern day computer systems collect data which contains dates and times. Many times you will want to convert the data from one data type to another.
Today, I will be exploring the DATENAME() function. This function has 15 different input parameters that can be passed to change the resulting output.
In short, the function takes a date part and date/time variables as input returns the part that you want a character string data.
I will be exploring the four date part parameters that convert the variable to a time string.
DATE PART | PARAMETER TO USE |
HOUR | HH |
MINUTE | MI or N |
SECOND | SS or S |
TIME ZONE OFFSET | TZ |
The examples below are sample calls to the function. The inputs puts are valid date, null value and a empty string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
-- -- Functions to get date and time parts as TEXT -- -- Hour ~ varchar(2) ~ 1 to 24 SELECT DATENAME(HH, SYSDATETIME()) AS HOUR_A_TXT2, DATENAME(HH, NULL) AS HOUR_B_NULL, DATENAME(HH, '') AS HOUR_C_EMPTY GO -- Minute ~ varchar(2) ~ 0 to 60 SELECT DATENAME(MI, SYSDATETIME()) AS MINUTE_A_TXT2, DATENAME(N, SYSDATETIME()) AS MINUTE_B_TXT2, DATENAME(MI, NULL) AS MINUTE_C_NULL, DATENAME(N, '') AS MINUTE_D_EMPTY GO -- Second ~ varchar(2) ~ 0 to 60 SELECT DATENAME(SS, SYSDATETIME()) AS SECOND_A_TXT2, DATENAME(S, SYSDATETIME()) AS SECOND_B_TXT2, DATENAME(SS, NULL) AS SECOND_C_NULL, DATENAME(S, '') AS SECOND_D_EMPTY GO -- Time Zone Offset ~ varchar(6) SELECT SYSDATETIMEOFFSET() AS FULL_DATE4, DATENAME(TZ, SYSDATETIMEOFFSET()) AS TZ_OFFSET_TXT6, DATENAME(TZ, NULL) AS TZ_OFFSET_NULL, DATENAME(TZ, '') AS TZ_OFFSET_EMPTY GO |
The output from the test is listed below. It is surprising that an empty string returns a selected default value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
output: HOUR_A_TXT2 HOUR_B_NULL HOUR_C_EMPTY ------------------------------ ------------------------------ ------------------------------ 14 NULL 0 (1 row(s) affected) MINUTE_A_TXT2 MINUTE_B_TXT2 MINUTE_C_NULL MINUTE_D_EMPTY ------------------------------ ------------------------------ ------------------------------ ------------------------------ 32 32 NULL 0 (1 row(s) affected) SECOND_A_TXT2 SECOND_B_TXT2 SECOND_C_NULL SECOND_D_EMPTY ------------------------------ ------------------------------ ------------------------------ ------------------------------ 56 56 NULL 0 FULL_DATE4 TZ_OFFSET_TXT6 TZ_OFFSET_NULL TZ_OFFSET_EMPTY ---------------------------------- ------------------------------ ------------------------------ ------------------------------ 2013-11-29 14:32:56.3175168 -05:00 -05:00 NULL +00:00 |
A brief summary of this article, pass one of the four ate part parameters to extract the time in a string format.