I have a column of dates with no delimiters. The column is nvarchar. The strings are consistent in length and format of MMDDYYYY. How can I convert these values to datetime?
edit - this question is in reference to sql server.
BEGIN
DECLARE @d DATETIME
DECLARE @s NVARCHAR(32)
SET @s = N'12012013'
SET @d = SUBSTRING(@s, 5,4) + SUBSTRING(@s, 1,2) + SUBSTRING(@s, 3,2)
SELECT @d
END
You just have to mangle the string into a format SQL server can parse correctly into a date. In the above it's the YYYYMMDD format.
EDIT Removed "-"'s because French language settings break them.
CONVERTYYYY-MM-DD format isn't safe for implicit conversion to datetime. On the other hand, YYYYMMDD is, and so you could simplify your code down to just two SUBSTRING calls: SUBSTRING(@s, 5, 4) + SUBSTRING(@s, 1, 4).First change the format to the one that always works no matter what server settings (YYYYMMDD) using two simple string functions, then convert to datetime:
declare @datestring varchar(8) = '11302012';
select CONVERT(datetime, RIGHT(@datestring, 4) + LEFT(@datestring, 4)) ConvertedDatetime;
cast(column as datetime)?