Filter null or empty input using LOAD DATA INFILE in MySQL

可紊 提交于 2019-12-06 05:19:29
Jordan Running

I would do this by filtering the file with grep or awk and then piping it into MySQL (via /dev/stdin). Something like this:

cat your_file.txt |
  awk '/\t.+/' |
    mysql -u your_username -pyour_password \
      -e "LOAD DATA LOCAL INFILE '/dev/stdin' \
          IGNORE INTO TABLE tablename         \
          COLUMNS TERMINATED BY '\t'          \
          LINES TERMINATED BY '\n'            \
          (col1, col2);" \
      your_database_name

The regular expression given to awk on the second line just matches any line that has a tab character followed by one or more of any character. You might want to tweak it to fit your needs.

Edit: One other possibility occurred to me. You could use SET to set some magic value on columns that are blank and put a BEFORE INSERT trigger on the table that will bail on a row when it sees that value. I don't have much experience with triggers but I think something like this should work:

CREATE TRIGGER skip_magic_rows
  BEFORE INSERT ON tablename
  FOR EACH ROW
  BEGIN
    IF NEW.col2 = 'IDSPISPOPD4815162342' THEN  # Some unlikely magic string
      # Trigger an error, which will cause the INSERT to fail†

      # If you have MySQL < 5.5 this is kludgy -- see Note 1
      DROP TABLE `Skipped row`

      # OR

      # In MySQL >= 5.5 you can send a signal--'45000' is a generic error
      SIGNAL SQLSTATE '45000' SET message_text = 'Skipped row';  # See Note 2

    END IF
  END
;

†: Per the docs:

An error during either a BEFORE or AFTER trigger results in failure of the entire statement that caused trigger invocation.

Then...

LOAD DATA LOCAL INFILE 'file' 
  IGNORE INTO TABLE tablename 
  COLUMNS TERMINATED BY '\t' 
  LINES TERMINATED BY '\n'
  (col1, @var2)
  SET col2 = IF(@var2 IN (NULL, ''), 'IDSPISPOPD4815162342', @var2)
;

Hope it's helpful!

Note 1: Relevant blog post and comments
Note 2: Relevant SO thread

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