Handling mmddyyyy VARCHAR to DATETIME Conversion in SQL Server
Directly converting mmddyyyy formatted strings to DATETIME in SQL Server often leads to errors. This is because the standard CONVERT
function expects a specific date format. This article provides a robust solution for this common problem.
Here's a reliable method:
<code class="language-sql">DECLARE @Date VARCHAR(8) SET @Date = '12312009' SELECT CONVERT(DATETIME, RIGHT(@Date, 4) + '-' + LEFT(@Date, 2) + '-' + SUBSTRING(@Date, 3, 2))</code>
This code functions as follows:
RIGHT
function extracts the year (last four characters).LEFT
function extracts the month (first two characters).SUBSTRING
extracts the day (characters 3 and 4).yyyy-mm-dd
string.CONVERT
transforms this string into a DATETIME value.This technique overcomes the limitations of a simple CONVERT
by explicitly rearranging the string components into the correct order for SQL Server's DATETIME interpretation, effectively resolving out-of-range errors. This ensures accurate and reliable conversion of mmddyyyy strings to the DATETIME data type.
The above is the detailed content of How to Convert mmddyyyy VARCHAR Strings to DATETIME in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!