【问题标题】:How to convert from text to boolean with consideration of value in PostgreSQL如何在考虑 PostgreSQL 中的值的情况下从文本转换为布尔值
【发布时间】:2017-05-15 11:44:52
【问题描述】:

我想将表中列的数据类型从text 转换为boolean。列中的数据为't' 为真,'f' 为假。

我试图用这个语句来转换它:

ALTER TABLE public.checktypes ALTER COLUMN deleted SET DATA TYPE boolean USING deleted::boolean;

这适用于数据类型的转换就好了。问题是,他们现在都是false。我该如何做到这一点,如果转换前的值为't',则布尔值将设置为true?

【问题讨论】:

    标签: sql postgresql type-conversion


    【解决方案1】:
    ALTER TABLE mytabe ALTER COLUMN mycolumn DROP DEFAULT;
    ALTER TABLE mytabe ALTER mycolumn TYPE bool USING CASE WHEN mycolumn=0 THEN FALSE ELSE TRUE END;
    ALTER TABLE mytabe ALTER COLUMN mycolumn SET DEFAULT FALSE;
    

    【讨论】:

      【解决方案2】:

      第一:

      update checktypes
      set deleted = case deleted when 't' then '1' when 'f' then '0' end
      

      然后:

      ALTER TABLE public.checktypes ALTER COLUMN deleted SET DATA TYPE boolean USING deleted::boolean;
      

      【讨论】:

        【解决方案3】:

        你可以试试这个方法: 创建临时表,插入并将文本转换为布尔值到临时表,删除旧列,添加布尔类型的新列并调用更新

        显示此代码:

        create table _temp
        (
            id integer,
            val_boolean boolean
        )
        
        insert into _temp(id,value) select id,val::boolean from your_table;
        
        alter table your_table drop column val;
        
        alter table your_table add column val boolean;
        
        update your_table t set val = (select val_boolean from _temp te where te.id = t.id);
        

        【讨论】:

          猜你喜欢
          • 2015-03-26
          • 2015-02-28
          • 2015-09-29
          • 2017-10-06
          • 2020-12-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多