Mysql:Trim all fields in database

前端 未结 7 2024
耶瑟儿~
耶瑟儿~ 2021-02-12 08:37
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条回答
  •  不要未来只要你来
    2021-02-12 09:09

    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
    

提交回复
热议问题