1

I have a problem with string to datetime conversion in SQL Server 2005.

If use Convert(datetime, x) in a where statement like this:

SELECT ThumbId
FROM [ImageBankSQL].[dbo].[MetaData]
WHERE (DataKey = 'ImagePropertyTagExifDTOrig'
       OR DataKey='ImagePropertyTagDateTime')
AND CONVERT(datetime, DataValue, 120) > CONVERT(datetime, '2011-09-23 00:00:00', 120)

I get:

Conversion failed when converting datetime from character string

But if I select the converted datetime instead of using them in the where statement, everything is fine, and I get my converted dates:

SELECT ThumbId, Convert(datetime, DataValue, 120), Convert(datetime, '2011-09-23 00:00:00', 120)
FROM [ImageBankSQL].[dbo].[MetaData]
WHERE (DataKey = 'ImagePropertyTagExifDTOrig'
       OR DataKey = 'ImagePropertyTagDateTime')

In both examples I have used both Convert(datetime, DataValue, 120) and Convert(datetime, DataValue) with the same results.

Why can I convert in select, but not in where? And how would I make my first query with convert in the where statement work?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
SimonHL
  • 175
  • 5
  • 14

1 Answers1

0

When you do the select, the conversion is only applied to the DataValue that meet your criteria (i.e. DataKey = 'ImagePRopertyTagDateTime')

SQL Server does not perform lazy evaluation, so with the Convert in the where clause, it will be evaluated against all rows, even when the DataValue is not suitable for parsing as a date.

paul
  • 21,653
  • 1
  • 53
  • 54