x

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
1k 74 80 83

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
19.1k 1 3 11

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 ♦
33.3k 13 20 44

(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.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

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

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x91
x33
x21

asked: Feb 24 '11 at 03:30 PM

Seen: 795 times

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