views:

80

answers:

3

I have column with varchar values like "022008" that I need to convert into a datetime like "02/01/2008". This will run on millions of records for a conversion process. What is an efficient select statement for doing this?

+1  A: 

Have a look here:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_str-to-date http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

The STR_TO_DATE function does just what it sounds like it would do: it takes a string, and turns it into a standard date object. To get it into the MM/DD/YYY format, you use DATE_FORMAT. This is the simplest way to do this, and is probably the most efficient.

For your example, you can convert it like so:

SELECT DATE_FORMAT(STR_TO_DATE('022008', '%m%Y'), '%m/%d/%Y');
-> 02/00/2008

You'll have to do some extra nonsense to get the day to read "01", so perhaps you could clean this up once you get the results back; otherwise, the query becomes more complicated.

Hope this helps.
-tjw

Travis J Webb
Seems like we're looking for MS Transact-SQL, though. And "efficient" is the word that makes this a tough one...
LesterDove
+1 clean and simple, you just forgot another 0 :)
medopal
This is valid for MySQL, not SQL Server.
OMG Ponies
A: 

Not hugely efficient, but my first stab at it:

declare @s as char(6)
set @s = '031977'

select dateadd(month, cast(substring(@s, 1, 2) as int) - 1, dateadd(year, substring(@s, 3, 4) - 1900, 0))

Output:

1977-03-01 00:00:00.000
RedFilter
+1  A: 

How about something like:

SET DATEFORMAT MDY
GO
Select StringValue, Cast(Stuff(StringValue, 3, 0, '-01-') As datetime)
From Table...

On a million rows on my local machine, that returned in 10 seconds.

Thomas
+1: Correct, and nice use of STUFF (SQL Server 2005+ supported) command: http://msdn.microsoft.com/en-us/library/ms188043%28SQL.90%29.aspx
OMG Ponies
Stuff was supported in SQL Server 2000, too.
G Mastros