The CONVERT, CAST, and PARSE/TRY_PARSE functions turn a character string into a DATE, DATETIME, or DATETIME2 value in SQL Server.
Use CAST or CONVERT when the input string is in an unambiguous ISO format like ‘2024-06-18’. Both functions succeed without specifying a style number.
CONVERT(data_type, expression, style) changes the data type of expression
. The optional style
argument tells SQL Server how to interpret the string (e.g., 101 = ‘mm/dd/yyyy’).
SELECT CONVERT(date, '06/18/2024', 101) AS order_date;
CAST(data_type AS target_type) is ANSI-SQL and portable. Use it when the string is already ISO-8601 or when you do not need a style code.
SELECT CAST(order_date AS date) FROM Orders;
TRY_CONVERT and TRY_PARSE return NULL when the conversion fails, preventing runtime errors in reports and data pipelines.
SELECT TRY_CONVERT(date, shipped_at, 103) -- 'dd/mm/yyyy'
, CASE WHEN TRY_CONVERT(date, shipped_at, 103) IS NULL THEN 'Bad Format' END AS warning
FROM Orders;
101 = U.S. ‘mm/dd/yyyy’, 102 = ANSI ‘yyyy.mm.dd’, 103 = U.K. ‘dd/mm/yyyy’, 126 = ISO8601 ‘yyyy-mm-ddThh:mi:ss’ (web APIs).
UPDATE Orders SET order_date = CONVERT(date, order_date_varchar, 126);
Always test with SELECT first to avoid data loss.
Store dates in DATE or DATETIME2, validate input at the application layer, prefer ISO-8601 strings, and wrap risky conversions in TRY_CONVERT.
TRY_CONVERT and TRY_PARSE were introduced in SQL Server 2012. For older versions, simulate with CASE and ISDATE().
Use DATE for calendar dates without time. Choose DATETIME2(3) or higher for timestamps; it offers more precision and a larger range than DATETIME.
No. You must pass the culture each time or rely on the server’s regional settings, which is discouraged for consistency.