需要将SQL列从varchar(255)转换为bigint(20)

时间:2012-11-27 23:35:23

标签: mysql sql casting

旧的Drupal 4.7评论表中的'thread'列是varchar(255),我需要将其转换为bigint(20),以使其适用于Wordpress wp_comments表中的'comment_parent'列。

我已经尝试了各种Cast和Convert命令,并且总是会遇到语法错误。

3 个答案:

答案 0 :(得分:2)

这适用于 SQL Server

create table Comments 
(
    [thread] nvarchar(255)
) 

insert comments 
select '1' 
union select '2' 
union select '3' 
union select '4' 
union select '5' 
union select 'x' 

select 
    case 
        when ISNUMERIC([thread]) > 0 
            then CAST([thread] as bigint) 
        else 
            null 
    end colAsBigInt 
    , [thread] colAsNvarChar 
from comments

http://sqlfiddle.com/#!6/337eb/1

对于 MySQL ,请尝试:

create table if not exists Comments 
(
    thread varchar(255) character set UTF8 not null
);

insert comments(thread) values ('1');
insert comments(thread) values ('2');
insert comments(thread) values ('3');
insert comments(thread) values ('4');
insert comments(thread) values ('5');
insert comments(thread) values ('6.1');
insert comments(thread) values ('x');

select 
    case 
        when thread  REGEXP ('^(-|\\+)?([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$') 
            then cast(thread as signed)
        else 
            null 
    end colAsBigInt 
    , thread colAsVarChar 
from comments

--regex trick from here: http://forums.mysql.com/read.php?60,1907,241284#msg-241284
--without the regex you'll get 0s instead of nulls for invalid values
--MySQL's cast only works on certain data types, given here http://www.roseindia.net/sql/mysql-example/mysql-cast.shtml

这里的Runnable MySQL示例:http://sqlfiddle.com/#!2/6d848/9

答案 1 :(得分:1)

当我运行你为MySQL提供的第二组代码时,它没有将该列转换为BigInt。它确实对colasBigInt和colasVarChar进行了并列比较。毫无例外,对于数千行,无论colasVarChar值如何,所有colasBigInt都读为Null。

答案 2 :(得分:0)

您获得的语法错误是什么?你在用什么数据库?

您可以提供的信息越多,有人可以帮助您的可能性就越大。