Try out type-safe date functions
In this exercise, we will try out the TRY_CONVERT()
, TRY_CAST()
, and TRY_PARSE()
set of functions. Each of these functions will safely parse string data and attempt to convert to another type, returning NULL
if the conversion fails. Conversion to, e.g., a date type can fail for several reasons. If the input string is not a date, conversion will fail. If the input type is in a potentially ambiguous format, conversion might fail. An example of this is the date 04/01/2019 which has a different meaning in the United States (April 1, 2019) versus most European countries (January 4th, 2019).
This exercise is part of the course
Time Series Analysis in SQL Server
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
DECLARE
@GoodDateINTL NVARCHAR(30) = '2019-03-01 18:23:27.920',
@GoodDateDE NVARCHAR(30) = '13.4.2019',
@GoodDateUS NVARCHAR(30) = '4/13/2019',
@BadDate NVARCHAR(30) = N'SOME BAD DATE';
SELECT
-- Fill in the correct data type based on our input
___(DATETIME2(3), @GoodDateINTL) AS GoodDateINTL,
-- Fill in the correct function
___(DATE, @GoodDateDE) AS GoodDateDE,
___(DATE, @GoodDateUS) AS GoodDateUS,
-- Fill in the correct input parameter for BadDate
___(DATETIME2(3), ___) AS BadDate;