x
login about faq Site discussion (meta-askssc)

Error when converting datetime from character string

I've googled this and plenty about this in the web but I am not sure why my string is not converting to datetime.

Any ideas?

SELECT gi.ITEM_NUM
,i.DSCR
 ,CAST(CASE WHEN (cast(MAX(CRTE_DTS) as datetime)) > DATEADD(d,-7,GETDATE()) THEN 1 ELSE 0 END  AS BIT) AS RECENT_ADD
FROM DAMART.dbo.T_x_ITEM AS gi
INNER JOIN DB.dbo.T_ITEM AS i
ON i.ITEM_NUM = gi.ITEM_NUM
more ▼

asked Feb 24 '11 at 03:30 PM in Default

siera_gld gravatar image

siera_gld
936 52 70 74

Here is the actual date stored in the db

Oct 4 2007 2:41PM

Feb 24 '11 at 03:43 PM siera_gld
(comments are locked)
10|1200 characters needed characters left

2 answers: sort oldest

Is that the only row in the table?

If not, it's quite likely there is at least one non-date string value stored in the CRTE_DTS column.

Try this to search for offending values:

SELECT CRTE_DTS 
FROM DAMART.dbo.T_x_ITEM AS gi
INNER JOIN DB.dbo.T_ITEM AS i
ON i.ITEM_NUM = gi.ITEM_NUM 
WHERE ISDATE(CRTE_DTS) = 0
more ▼

answered Feb 24 '11 at 03:57 PM

KenJ gravatar image

KenJ
12.4k 2 10

UR Awesome

Feb 24 '11 at 04:06 PM siera_gld
(comments are locked)
10|1200 characters needed characters left

How is the date represented in the database?

What's the result of just running "SELECT MAX(CRTE_DTS) FROM... (wherever)"

I've just tried the following, and it's worked quite happily, so I'm reckoning there might be some extra data that's floating to the top of the "MAX" calculation...

DECLARE @t VARCHAR(20)
SELECT @t = 'Oct 4 2007 2:41PM'
SELECT cast(@t as datetime)

... either that, or you've got some strange localisation settings.

more ▼

answered Feb 24 '11 at 03:50 PM

ThomasRushton gravatar image

ThomasRushton ♦
29.5k 6 9 36

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments



Facebook logo Follow Ask SSC on Facebook
Find Ask SSC on Google+
linkedin logo Find us on LinkedIn

Topics:

x84
x30
x17

asked: Feb 24 '11 at 03:30 PM

Seen: 522 times

Last Updated: Feb 24 '11 at 03:45 PM

Copyright © 2002-2012 Simple Talk Publishing. All Rights Reserved. If you have any queries, please contact the site administrators.
Ask SQL Server Central is a community service provided by Red Gate.