Guest
Public paste!

Stata odbc with dates v1.1

By: a guest | May 23rd, 2010 | Syntax: None | Size: 2.06 KB | Hits: 428 | Expires: Never
Copy text to clipboard
  1. capture program drop odbc2create
  2. *! version 1.1
  3.  * Update 5/23: Now checks if there are any date columns.  Simple commands if not.
  4.  * Modified ODBC command that takes all Stata dates and inserts as DATE
  5.  * Written for MySQL.  Drops the table in question if it exists already.
  6.  * Only use with create.  If you are appending an existing table, then you need to do the date conversion in Stata.
  7.  * By Michael Ewens with invaluable guidance from Joseph Coveney
  8.  * Built from this thread: http://www.stata.com/statalist/archive/2010-05/msg01190.html
  9.  *  5-20-2010
  10.  * syntax odbc2create, [t]able(string) dsn() u()
  11.  version 7.0
  12.  program define odbc2create
  13.     syntax [varlist], Table(string)  [*]
  14.     if ("`varlist'" == "") {
  15.            local varlist _all
  16.        }
  17.        else {
  18.            * no op
  19.        }
  20.    
  21.     * Get a list of the date variables
  22.     local date_vars
  23.     local count = 0
  24.         foreach variable of varlist `varlist' {
  25.             local variable_format : format `variable'
  26.             if (strpos("`variable_format'", "%t") == 1) {
  27.                 * May not have any dates
  28.                 local count = `count' + 1
  29.                 local date_vars `date_vars' `variable'
  30.             }
  31.             else {
  32.                
  33.             }
  34.         }
  35.    
  36.     * Drop if table exists
  37.     local string "DROP TABLE IF EXISTS "
  38.     local drop_s `string'`table'
  39.  
  40.     if(`count' == 0) {
  41.          odbc exec("`drop_s'"), `options'
  42.          odbc insert `varlist', table("`table'") create `options'
  43.     }
  44.     else {
  45.        
  46.         * Format the date for MySQL
  47.         format `date_vars' %tdCCYY-NN-DD
  48.         preserve
  49.             qui tostring `date_vars', force replace usedisplayformat
  50.             odbc exec("`drop_s'"), `options'
  51.             * Create table
  52.             odbc insert `varlist', table("`table'") create `options'
  53.             * Alter columns for date
  54.             foreach variable of varlist `date_vars' {
  55.                    odbc exec("ALTER TABLE `table' MODIFY `variable' DATE"), `options'
  56.                }
  57.        
  58.         restore
  59.     }
  60.  end