Sunday, March 16, 2014

While trying to migrate Microsot SQL Server data into DB2, I've stumbled into errors that originated from the difficulty to convert Microsoft's datetime type where the milliseconds were populated into DB2's type timestamp.
One solution would be to write a script that will go over all tables in the SQL Server and zero the milliseconds:

-- Zero the milliseconds in all tables for columns of type datetime
-- In the next clause use the relevant DB name
USE MyDB;
GO
 

DECLARE @mytblname varchar(255), @mycolname varchar(255);
 

DECLARE TheCursor CURSOR FOR
SELECT table_name, column_name FROM information_schema.columns where DATA_TYPE = 'datetime' order by table_name;
 

OPEN TheCursor;
 

FETCH NEXT FROM TheCursor INTO @mytblname, @mycolname;
WHILE @@FETCH_STATUS = 0
BEGIN
dateadd(millisecond,datepart(millisecond,@mycolname)*-1,@mycolname) where datepart(millisecond,@mycolname) <> 0;
    EXECUTE ('UPDATE dbo.' + @mytblname + ' SET ' + @mycolname + '= dateadd(millisecond,datepart(millisecond,' + @mycolname + ')*-1,' + @mycolname + ') where datepart(millisecond,' + @mycolname +') <> 0;')
    FETCH NEXT FROM TheCursor INTO @mytblname, @mycolname
END;
 

CLOSE TheCursor;
DEALLOCATE TheCursor;
GO