Update multiple columns that start with a specific string

后端 未结 2 1315
既然无缘
既然无缘 2021-01-22 18:15

I am trying to update a bunch of columns in a DB for testing purposes of a feature. I have a table that is built with hibernate so all of the columns that are created for an emb

2条回答
  •  不知归路
    2021-01-22 18:44

    There's no handy shortcut sorry. If you have to do this kind of thing a lot, you could create a function to dynamically execute sql and achieve your goal.

    CREATE OR REPLACE FUNCTION reset_cols() RETURNS boolean AS $$ BEGIN 
        EXECUTE (select 'UPDATE table SET ' 
                      || array_to_string(array(
                                  select column_name::text 
                                  from information_schema.columns 
                                  where table_name = 'table' 
                                  and column_name::text like 'contact_info_address_%'
                         ),' = NULL,') 
                      || ' = NULL'); 
        RETURN true; 
     END; $$ LANGUAGE plpgsql;
    
    -- run the function
    SELECT reset_cols();
    

    It's not very nice though. A better function would be one that accepts the tablename and column prefix as args. Which I'll leave as an exercise for the readers :)

提交回复
热议问题