Updating empty string to NULL for entire database

爱⌒轻易说出口 提交于 2019-12-22 14:54:43

问题


I'm performing some database clean up and have noticed that there are a lot of columns that have both empty strings and NULL values in various columns.

Is it possible to write an SQL statement to update the empty strings to NULL for each column of each table in my database, except for the ones that do not allow NULL's?

I've looked at the information_schema.COLUMNS table and think that this might be the place to start.


回答1:


It's not possible to do this with one simple SQL statement.

But you can do it using one statement for each column.

UPDATE TABLE SET COLUMN = NULL
WHERE LENGTH(COLUMN) = 0

or, if you want to null out the items that also have whitespace:

UPDATE TABLE SET COLUMN = NULL
WHERE LENGTH(TRIM(COLUMN)) = 0



回答2:


I don't think it's possible within MySQL but certainly with a script language of your choice.

  1. Start by getting all tables SHOW TABLES
  2. Then for each table get the different columns and find out witch ones allow null, either with DESC TABLE, SHOW CREATE TABLE or SELECT * FROM information_schema.COLUMNS, take the one you rather parse
  3. Then for each column that allows null run a normal update that changes "" to null.

Prepare to spend some time waiting :)




回答3:


I figured out how to do this using a stored procedure. I'd definitely look at using a scripting language next time.

DROP PROCEDURE IF EXISTS settonull;

DELIMITER //

CREATE PROCEDURE settonull()
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE _tablename VARCHAR(255);
  DECLARE _columnname VARCHAR(255);
  DECLARE cur1 CURSOR FOR SELECT 
                           CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS table_name,
                           COLUMN_NAME AS column_name 
                           FROM information_schema.COLUMNS 
                           WHERE IS_NULLABLE = 'YES' 
                           AND TABLE_SCHEMA IN ('table1', 'table2', 'table3');

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

  read_loop: LOOP
    FETCH cur1 INTO _tablename, _columnname;

    IF done THEN
      LEAVE read_loop;
    END IF;

    SET @s = CONCAT('UPDATE ', _tablename, ' SET ', _columnname, ' = NULL WHERE LENGTH(TRIM(', _columnname, ')) = 0' );
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

  END LOOP;

  CLOSE cur1;
END//

DELIMITER ;

CALL settonull();


来源:https://stackoverflow.com/questions/8362245/updating-empty-string-to-null-for-entire-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!