简体   繁体   English

将2个varchar属性转换为日期时间时出错

[英]Error converting 2 varchar attributes to datetime

I have a database where the CREATEDATE and CREATETIME are stored in 2 separate attributes as varchars. 我有一个数据库,其中CREATEDATECREATETIMECREATETIME形式存储在2个单独的属性中。 I'm trying to combine these 2 into a single smalldatetime attribute. 我试图将这两个合并为一个smalldatetime属性。

When I run the following conversion, I receive the error: 当我运行以下转换时,我收到错误:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

UPDATE UsersTemp
SET Created =   CONVERT(datetime, CAST(CONVERT(date, CreateDateIMF, 102)AS varchar(50)) 
            + ' ' +
            CASE WHEN LEN(CreateTime) = 6 THEN 
                 Left(CreateTime, 2) + ':' + SUBSTRING(CreateTime, 2, 2)
            ELSE 
                 Left(CreateTime, 1) + ':' + SUBSTRING(CreateTime, 1, 2)
            END
            + ':' + Right(CreateTime, 2), 120)

(Yes this is messy SQL, but it's only temporary to get this data in a way I can use it better) (是的,这是一堆乱七八糟的SQL,但是以一种我可以更好地使用它的方式来获取这些数据只是暂时的)

I have tried a number of different things when working with the whole set and I can't seem to get it to work. 与整套设备一起使用时,我尝试了许多不同的操作,但似乎无法正常工作。

When trying the above parameters in a SELECT , the date works fine, so the problem exists in the time field but I'm not sure how to correct it. SELECT尝试上述参数时,日期工作正常,因此时间字段中存在问题,但我不确定如何更正。

Example Original Data: 示例原始数据:

CREATEDATEIMF
 20120220
 20040415
 20040415
 20040415
 20040415
 20040415
 20040415
 20040415
 20040415
 20050510

CREATETIME
 160401
 142304
 142304
 142304
 142304
 142304
 142304
 142304
 142304
 44427

I have confirmed that the time is HMMSS. 我已经确认时间是HMMSS。 (note there are no leading 0's on the short hours) (请注意,短时间内没有前导0)

This data is a dump from an old COBOL program. 此数据是旧的COBOL程序的转储。

DECLARE @x TABLE (CREATEDATE VARCHAR(32), CREATETIME VARCHAR(32));

INSERT @x VALUES
('20120101','142304'),
('20120101','44427');

SELECT CONVERT(DATETIME, 
  CREATEDATE + ' ' + STUFF(STUFF(RIGHT('00' 
  + CREATETIME, 6), 5, 0, ':'), 3, 0, ':'))
FROM @x;

So in your case, 所以就你而言

UPDATE dbo.UsersTemp SET Created = CONVERT(DATETIME, 
  CREATEDATE + ' ' + STUFF(STUFF(RIGHT('000000' 
  + CREATETIME, 6), 5, 0, ':'), 3, 0, ':'));

Now, since you chose to store date/time data using the wrong data type, there is no guarantee that all of the values you have in there will in fact convert appropriately. 现在,由于您选择使用错误的数据类型存储日期/时间数据,因此无法保证其中的所有值实际上都会正确转换。

SELECT RIGHT('000000' + CAST(createtime AS VARCHAR(6)), 6) paddedCreateTime
FROM yourTable

should make the 44427 look like 044427 but I'm not sure if this is where your problem is 应该使44427看起来像044427,但是我不确定这是否是您的问题所在

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM