使用SQL 2012管理工作室将varchar数据类型转换为datetime数据类型

时间:2014-07-20 00:24:56

标签: sql-server-2012

我有一个ddmmmyyyy:hh:mm:ss.nnnnnn列,它存储为varchar(25)。我需要将它作为日期时间保存在同一列中。我尝试过使用

update tablename
set columnname = (SUBSTRING(columnname,1,2) + '-' + SUBSTRING(columnname,3,3) + '-' + 
SUBSTRING(columnname,6,4) + ' ' + SUBSTRING(columnname,11,8));

然后

alter table tablename    
alter columnname datetime;

但稍后会显示错误

Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

如何更改上述查询的任何其他意见或任何修改。请帮忙。谢谢。

2 个答案:

答案 0 :(得分:1)

根据您提供的字符串格式,您应该使用datetime2数据类型

你的字符串格式几乎是正确的,年后只有1个冒号。

如果您修复了该问题,可以直接将varchar字段转换为datetime2。例如,首先您可以通过运行以下查询

来用空格替换额外的冒号
UPDATE myTable
    SET targetColumn = STUFF ( targetColumn , 10, 1, ' ')
-- ddmmmyyyy:hh:mm:ss.nnnnnn
--           \
--           this colon is extra which is at 10th position

在此之后,您可以直接ALTER您的表格,并将数据类型更改为datetime2

重要提示:所有行中的数据必须包含有效日期

这是一个测试,显示如何转换

CREATE TABLE testTable(testCol varchar(25));

INSERT INTO testTable(testCol)
    VALUES('03Jan2014 18:33:39.999999');

ALTER TABLE testTable ALTER COLUMN testCol datetime2;

SELECT  *
FROM    testTable

DROP TABLE testTable;

答案 1 :(得分:0)

添加新列

alter table t
add n datetime

更新新列

update t
set n = datetimefromparts(
            cast(substring(o,6,4) as int),
            case substring(o,3,3)
                 when 'jan' then 1
                 ...
                 when 'dec' then 12
            end,
            cast(substring(o,1,2) as int),
            cast(substring(o,11,2) as int),
            cast(substring(o,14,2) as int),
            cast(substring(o,17,2) as int),
            cast(substring(o,20,6) as int)
        )

如果您需要删除旧列

alter table t
drop column o
相关问题