繁体   English   中英

迁移以将字符串数组转换为整数

[英]Migration to convert array of string to integer

将字符串的data_type数组的列template_id转换为整数的迁移是什么?

例:

行的template_id值为[“ 2”]。 我希望它是2。

template_id的所有值在数组中都有一个元素。

我会推荐以下方法来做到这一点

  1. 使用数据类型int创建一个新字段temp_template_id
  2. template_id所有值插入temp_template_id
  3. 删除列template_id
  4. 将列temp_template_id重命名为template_id

一种。 rails g迁移AddTempTemplateDataToTableName

def change
  add_column :table_name, :temp_template_id, :integer
end

b。 rails g迁移RenameColumnTemptemplateID

def self.up
  # Script to fill column `temp_template_id` from 'template_id'
  remove_column :table_name, :template_id
  rename_column :table_name, :temp_template_id, :template_id
end

def self.down      
  rename_column :table_name, :template_id, :temp_template_id
  add_column :table_name, :template_id, :array, :default => []
  # Script to fill column `template_id` from 'temp_template_id'
end

SQL迁移就像using n[1]一样容易:

t=# create table t3(n int[]);
CREATE TABLE
t=# insert into t3 select array[2];
INSERT 0 1
t=# select * from t3;
  n
-----
 {2}
(1 row)

t=# alter table t3 alter COLUMN n type int using n[1];
ALTER TABLE
t=# select * from t3;
 n
---
 2
(1 row)

并且如果您的数组不是int[] ,则需要两次转换为avoiod

错误:列“ template_id”的USING子句的结果无法自动转换为类型整数提示:您可能需要添加显式转换。

alter table t3 alter COLUMN n type int using n[1]::text::int;

应该可以解决问题,例如以下示例:

t=# create table t3(n text[]);
CREATE TABLE
t=# insert into t3 select array[2];
INSERT 0 1
t=# select * from t3;
  n
-----
 {2}
(1 row)

t=# alter table t3 alter COLUMN n type int using n[1]::text::int;
ALTER TABLE
t=# select * from t3;
 n
---
 2
(1 row)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM