简体   繁体   中英

MySQL: Whole database, convert [empty] values to NULL

I'm working on a database where there is a mix of NULL and '' (empty) values. I would like to convert all empty values to NULL .

Something like

UPDATE table SET col=NULL WHERE col=''

but for the whole database


notes:

  • I've changed default values to NULL

  • I'm well aware of the NULL vs '' debate, and this isn't something i really want to go into (plenty of other questions on SO for that)

There probably is a better solution, but you could always do a mysql dump of the base, and then parse the .sql file, replacing '' with NULL. For parsing, you could use custom made php script, or some other way - that part shouldn't be hard :)

This worked for me:

$tables = {array of table names};

foreach($tables as $t){
    $cols = FALSE;
    $q = "SELECT * FROM $t LIMIT 1";
    $res = mysql_query($q);
    while ($r = mysql_fetch_array($res, MYSQL_ASSOC)){    
        $cols = array_keys($r);
    }
    if($cols){
        foreach($cols as $c){
            $q2 = "UPDATE $t SET $c=NULL WHERE $c = ''";
            mysql_query($q2);
            echo mysql_error();
        }
    } 
}

最快的方法可能只是转储,使用文本编辑器搜索/替换然后加载。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM