views:

79

answers:

1

Hello I'm doing some data conversion from PostgreSQL to Microsoft SQL Server. So far it has all went well and I almost have the entire database dump script running. There is only one thing that is now messed up: dates.

The dates are dumped to a string format. These are two example formats I've seen so far: '2008-01-14 12:00:00' and the more precise '2010-04-09 12:23:45.26525'

I would like a regex (or set of regexs) that I could run so that will replace these with SQL Server compatible dates. Anyone know how I can do that?

+1  A: 

The first is compatible with datetime, but the second is too precise. It will fit in sqldatetime2, which is available from SQL Server 2008:

select cast('2008-01-14 12:00:00' as datetime)
,      cast('2010-04-09 12:23:45.26525' as datetime2)

For an earlier version, you can use substring to chop off the unstorable precision:

select cast(substring('2010-04-09 12:23:45.26525',1,23) as datetime)

For a regex to remove any additional digits (using perl regex syntax):

(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{3})\d*

And replace with:

$1

Which is matches the regex part between () brackets.

Andomar
Changing our datetime columns to sqldatetime2 is not an option though. We do not need the extra precision, it's just that timestamp is the only datetime-ish format in PostgreSQL
Earlz
@Earlz: If you don't need the extra precision, use `substring` to remove it. SQL Server recognizes the `HH:mm:ss.fff` format for microseconds
Andomar
Yes but your solution is not complete. I'm dealing with a multi thousand line file. What would be a regex to match this date so I can replace it with a `cast(substring... ` bit?
Earlz
@Earlz: SQL Server does not support regexes... in what language would you like to do the regex replace? Have you tried SQL Server's text import wizard, which is fairly powerful?
Andomar
@Ando no I have a huge text file containing the SQL code dumped from a PostgreSQL database. I am converting the text so that I can restore the data from Postgres to SQL Server. The regex only needs to run in a text editor.
Earlz
@Earlz: Added a perl compat regex
Andomar