views:

315

answers:

2

The short story is I have a SQL Server DB with varchar fields instead of datetime (don't ask, it's a long story and can't be fixed). Somehow we've recently been getting weird / random characters inserted in these fields instead of what should be there (either NULL, '' or YYYY-MM-DD). Something like this: '?+x' with high-bit ascii characters.

The report uses this query to help massage the data into something usable (only relevant parts posted here):

SELECT CASE WHEN c.CallStatus = 'Closed' THEN CAST(c.ClosedDate + ' ' + c.ClosedTime as datetime) ELSE NULL END as 'Closed Date'
WHERE CAST(c.closeddate AS DATETIME) BETWEEN  @StartDate AND @EndDate

but it is choking on this new bad data.

My question is this:

How can I update the query to ignore the bad data so I can get the reports to run while I hunt down the source of the bad data? My first priority is to get the reports to function, second is to find and kill the source of bad data.

+5  A: 
CASE WHEN ISDATE(closeddate) = 1 THEN CAST(c.closeddate AS DATETIME) ELSE NULL END
Paul Creasey
I was going to post with ISDATE() in the WHERE clause. Either works.
Philip Kelley
Thanks, the original post was part of the WHERE clause (updated to be clearer). How would I update the WHERE clause (I think that's where it's failing)?
Randall
A: 

Looks to be all fixed, thankyouverymuch! here's my final result:

AND case WHEN ISDATE (closeddate) = 1 THEN CAST(c.closeddate AS DATETIME) ELSE NULL END BETWEEN @StartDate AND @EndDate

and now on to the hunt!

Randall