如何将字符串列更改为bigint? [英] How do I change a string column into a bigint?

查看:222
本文介绍了如何将字符串列更改为bigint?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在rails迁移中。如何将字符串类型的列更改为bigint?



我有:

  t.change:ip_number_from,:integer,:limit => 8 

我得到:

  PG ::错误:错误:列ip_number_from无法转换为输入bigint 

我甚至尝试过2种方法:

  change_column:ip_to_countries,:ip_number_from,:integer,:limit => 8 
change_column:ip_to_countries,:ip_number_from,:bigint

仍然是同样的错误。 p>

解决方案

Postgres告诉你,该列中存在不知道如何转换的现有数据,因此它需要ALTER语句,为列提供USING子句以指定如何转换现有值。



不幸的是,您需要下拉数据库特定的代码来完成这个,或者使用类似于这里建议的解决方案:

http://webjazz.blogspot.co.uk/2010/03/how-to-alter-columns-in-postgresql.html



编辑:在迁移过程中,您可以直接在SQL中执行此操作:

 执行<< -SQL 
ALTER TABLE ip_to_countries
ALTER COLUMN ip_number_from TYPE bigint USING ip_ number_from :: bigint
SQL


In rails migration. How do I change a string type column to a bigint?

I have:

t.change :ip_number_from, :integer, :limit => 8

I get:

PG::Error: ERROR:  column "ip_number_from" cannot be cast to type bigint

I even tried with the 2 alternatives:

change_column :ip_to_countries, :ip_number_from, :integer, :limit => 8
change_column :ip_to_countries, :ip_number_from, :bigint

Still the same error.

解决方案

Postgres is telling you that there is existing data in that column which it doesn't know how to convert, so it needs an ALTER statement which supplies a USING clause for the column to specify how to cast existing values.

Unfortunately, you're going to need to drop down the database-specific code to accomplish this, or use something similar to the solution suggested here:

http://webjazz.blogspot.co.uk/2010/03/how-to-alter-columns-in-postgresql.html

Edit: Here's how you might do it directly in SQL in your migration:

execute <<-SQL
  ALTER TABLE ip_to_countries
  ALTER COLUMN ip_number_from TYPE bigint USING ip_number_from::bigint
SQL

这篇关于如何将字符串列更改为bigint?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆