如果我在SQL Server中执行以下查询,一切都很好:
SELECT convert(datetime, '580112', 12)
1958-01-12 00:00:00.000
但是当我执行此查询时:
SELECT TOP 1 [ID]
,[FirstName]
,[MiddleName]
,[LastName]
,CONVERT(datetime, [DateOfBirth], 12)
,[address]
,[city]
,[state]
,[zip]
,[phoneNumber]
FROM [dbo].[PF]
GO
我收到以下错误:
Msg 242, Level 16, State 3, Line 7
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
我的数据是这样的:
ID FirstName MiddleName LastName DateOfBirth address city state zip phonenumber
1 100 MARGARET P BIGGIO 580112 122 WALTHAM ST MAYNARD MA 01754 9788971581
编辑:
其他日期与yymmdd ISO格式相同:
DateOfBirth
531000
481023
500700
500200
570518
411100
580112
510100
840800
671200
680605
681216
430600
470701
470330
630206
470600
710914
620800
590100
DateOfBirth
是VARCHAR,是否必须将其强制转换为其他内容?
答案 0 :(得分:1)
@bsteo即将出现上述问题,因为日期值不能为00,为什么会出现错误,请参见下面的差异。
SELECT convert(datetime, '500700', 12)
Msg 242, Level 16, State 3, Line 3
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
与01日期相同的值
SELECT convert(datetime, '500701', 12)
1950-07-01 00:00:00.000
检查差异。
答案 1 :(得分:1)
所以您的数据不正确。
使用以下功能即可:
declare @tbl as table (ID int primary key identity, FirstName varchar(50), MiddleName varchar(50), LastName varchar(50),DateOfBirth varchar(50),address varchar(50),city varchar(50),state varchar(50),zip varchar(50),phonenumber varchar(50))
insert into @tbl ( FirstName, MiddleName, LastName, DateOfBirth, address, city, state, zip, phonenumber) values
( 'MARGARET', 'P', 'BIGGIO','531001','122','WALTHAM ST','MAYNARD MA','01754','9788971581')
select
[ID]
, [FirstName]
, [MiddleName]
, [LastName]
, convert(datetime, [DateOfBirth], 12) DateOfBirth
, [address]
, [city]
, [state]
, [zip]
, [phoneNumber]
from @tbl
但是当日期更改为531000
时,SQL无法读取它。
更正数据,然后您的查询将起作用。