2012-07-21 213 views
10

我知道将某些东西从较大的数据类型转换为较小的数据类型是非正统且潜在的危险。但是,在这种情况下,BIGINT UNSIGNED列的值不可能大于INT列的最大大小。将BIGINT UNSIGNED转换为INT

所以,使用MySQL,我正在阅读表结构。在阅读information_schema.columns.ordinal_position专栏时,我意识到它是BIGINT UNSIGNED。现在,我想将其作为INT来代替我的处理目的。我想在SQL中转换/转换类型。

CASTCONVERT只允许我改变数据类型的标志,显然。

SELECT CAST(ordinal_position AS SIGNED) 
FROM information_schema.columns 

我希望列专门作为INT返回。例如。切割色谱柱的最大值为INT并返回该值。

现在我只是在将值拉回来之后更改数据类型。但我想知道如何在SQL中完成它。

回答

6

this article似乎有一个解决方案:

Create the function that will perform the conversion:

CREATE FUNCTION BigToInt (n BIGINT) RETURNS INTEGER RETURN n;

As you can see, the function is very short and simple: It takes a BIGINT and immediately returns it as an ordinary integer. However, one consequence of this is that some of the data will be truncated down to the largest possible value for Int.

(想必你可以添加“无符号”的签名 - 如果没有你仍然可以投结合起来,你已经拥有了删除未签名的一部分)。

+1

有什么替代方法可以不创建函数?不得不记得在使用后拆卸功能是一件麻烦事。 – Pacerier 2015-01-26 13:01:41

0

如果您尝试创建函数的方式,你会得到这样的错误:

ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, 
or READS SQL DATA in its declaration and binary logging is enabled 
(you *might* want to use the less safe log_bin_trust_function_creators 
variable) 

查看如何解决此链接的详细信息:

http://dev.mysql.com/doc/refman/5.0/en/stored-programs-logging.html

+1

在这种特殊情况下,修正是添加'DETERMINISTIC'。 – dolmen 2016-01-07 17:53:11

1

我很遗憾没没有权利在我工作的数据库上创建功能,所以在尝试了几件事情之后,它可以工作:

ALTER TABLE table_name MODIFY column_name INTEGER; 

保存了我不得不重写15个外键。

相关问题