Tuesday, August 4, 2009

Converting TDW Timestamps in MySQL

Hope you read my previous articles on converting TDW Timestamps into "normal" timestamps in DB2 and in JavaScript (BIRT). Recently, I had to re-write this function in MySQL. In case you wonder, ITNM uses MySQL as the poll data collection database and again the same problem manifested.

The solution in MySQL is similar to that of DB2 based solution. Create a function in MySQL database and call that function in your SQL. But here is how to do it.

  1. Bring up MySQL Administrator client and connect to the database in question.
  2. Goto Catalogs in your left pane and select the appropriate database schema.
  3. Goto Stored Procedure tab and click the "Create Stored Proc".
  4. In the name field, give a Name for the function (e.g. TDW_TO_NORMAL_TS) and click "Create FUNCTION" button.
  5. MySQL will create a skeleton function like below.
    CREATE FUNCTION `ncpolldata`.`TDW_TO_NORMAL_TS` () RETURNS INT
    BEGIN
    END
  6. Replace the "CREATE FUNCTION" to look like below.
    CREATE FUNCTION `ncpolldata`.`TDW_TO_NORMAL_TS` (tdw_time bigint) RETURNS DATETIME DETERMINISTIC
  7. Between the "BEGIN" and "END" blocks, paste the following code.
    BEGIN
    Declare normal_time datetime;
    Declare tdw_trunc bigint;
    Set tdw_trunc = substr(tdw_time,2,12);
    Set normal_time = DATE_FORMAT(tdw_trunc, '%y%m%d%H%i%s');
    return(normal_time);
    END
  8. That's it. Click on the "Execute SQL" button to save the newly created function.
  9. Call the function in your SQL Statements like below.
    SELECT TDW_TO_NORMAL_TS(poll_time) from KNP_POLL_DATA_COLLECTION LIMIT 100
Hope you find this useful.

1 comment:

Venkat said...

For this function creation to work, you should set MYSQL system variable log_bin_trust_function_creators to 1. Connect to mysql command prompt (as root) and issue the following command.

mysql> SET GLOBAL log_bin_trust_function_creators = 1;

-venkat