Mysql:Trim all fields in database

前端 未结 7 1733
一生所求
一生所求 2021-02-12 08:20
UPDATE mytable SET mycolumn= LTRIM(RTRIM(mycolumn));

works fine on trimming columns removing trailer spaces, but how can i adjust it to trim all column

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-12 08:59

    I was actually looking for something similar for a legacy table that's constantly updated by an outside source when I came across this question. I realize the OP was looking for a purely SQL(MySQL) answer, but in case you use Rails, you might find this tidbit that I came up with helpful:

    MyModel.update_all(MyModel.columns.map(&:name).map{|x| "#{x} = TRIM(#{x})"}.join(', '))
    

    You can also wrap it into a class method in your model

    class MyModel < ActiveRecord::Base
      def self.trim_all
       update_all(columns.map(&:name).map{|x| "#{x} = TRIM(#{x})"}.join(', '))
     end
    end
    

    Then call it like this

    MyModel.trim_all
    

提交回复
热议问题