Data types and expressions
CAST, CONVERT, and safe conversions
Convert values deliberately and handle text that may not be convertible.
Lesson 20 of 84
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Beginner
On this page4 sections
This lesson uses the unmodified DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Convert values deliberately and handle text that may not be convertible.
Run the example
SELECT TOP (3) EmployeeID,
CAST(EmployeeID AS varchar(10)) AS EmployeeIDText,
CONVERT(varchar(10), HireDate, 23) AS ISODate
FROM dbo.Employees
ORDER BY EmployeeID;Read it step by step
- CAST(EmployeeID AS varchar(10)) turns an int into text in the result.
- CONVERT(varchar(10), HireDate, 23) produces a yyyy-mm-dd text value using SQL Server style 23.
- ORDER BY EmployeeID makes the TOP (3) sample reproducible. Neither conversion changes the stored columns.
Check the result
| EmployeeID | EmployeeIDText | ISODate |
|---|---|---|
| 1 | 1 | 2018-05-14 |
| 2 | 2 | 2021-02-15 |
| 3 | 3 | 2020-09-07 |
ISODate is text in this result; converting for display does not change HireDate in the table.
Practice
For ProductID 1, try converting the text 42 and the text not-a-number to int. Show both values.
Check your answer and expected result
Reveal answer
SELECT ProductID, TRY_CONVERT(int, N'42') AS ValidNumber,
TRY_CONVERT(int, N'not-a-number') AS InvalidNumber
FROM dbo.Products
WHERE ProductID = 1;| ProductID | ValidNumber | InvalidNumber |
|---|---|---|
| 1 | 42 | NULL |
The valid text becomes 42; the invalid text becomes NULL. The source product remains unchanged.
Your progress
Reveal the check answer or reach the end to complete this lesson.