In SQL Server, the CAST function is used to convert one data type to another. When dealing with dates, it’s common to use the CAST function to convert a string or another compatible data type to the DATE data type. The CAST function allows you to explicitly specify the target data type and perform the conversion.
Here’s an example of using CAST to convert a string to a DATE in SQL Server:
DECLARE @dateString NVARCHAR(10) = '2023-11-27'; DECLARE @convertedDate DATE; SET @convertedDate = CAST(@dateString AS DATE); SELECT @convertedDate AS ConvertedDate;
In this example, the @dateString variable is a string representing a date in the ‘YYYY-MM-DD’ format. The CAST function is then used to convert this string to the DATE data type, and the result is stored in the @convertedDate variable. Finally, the converted date is selected and displayed.
You can also use the CONVERT function, which is another way to achieve the same result:
-- Example 2: Using CONVERT to cast a string to a DATE DECLARE @dateString NVARCHAR(10) = '2023-11-27'; DECLARE @convertedDate DATE; SET @convertedDate = CONVERT(DATE, @dateString); SELECT @convertedDate AS ConvertedDate;
Both examples achieve the same result, and you can choose the method that you find more readable or convenient. It’s important to note that the input string must be in a format that SQL Server can recognize as a date, and the ‘YYYY-MM-DD’ format is commonly used for this purpose.
Make sure to adapt the examples to your specific requirements, and be aware of any potential issues with date formats or data integrity in your database.