簡體   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