Formatting dates with CAST() and CONVERT()
We can use the CAST()
function to translate data between various data types, including between date/time types and string types. The CONVERT()
function takes three parameters: a data type, an input value, and an optional format code.
In this exercise, we will see how we can use the CAST()
and CONVERT()
functions to translate dates to strings for formatting by looking at the (late) night the Chicago Cubs won the World Series in the US in 2016. In the process, we will see one difference between the DATETIME
and the DATETIME2
data types for CAST()
and the added flexibility of CONVERT()
.
Cet exercice fait partie du cours
Time Series Analysis in SQL Server
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
DECLARE
@CubsWinWorldSeries DATETIME2(3) = '2016-11-03 00:30:29.245',
@OlderDateType DATETIME = '2016-11-03 00:30:29.245';
SELECT
-- Fill in the missing function calls
___(___ AS DATE) AS CubsWinDateForm,
___(___ AS NVARCHAR(30)) AS CubsWinStringForm,
___(___ AS DATE) AS OlderDateForm,
___(___ AS NVARCHAR(30)) AS OlderStringForm;