SQL DateTime Conversion Fails when No Conversion Should be Taking Place

喜欢而已 提交于 2019-12-05 11:10:58

I've encountered this type of error before, it's due to the "order of operations" performed by the execution plan.

You are getting that error message because the execution plan for your statement (generated by the optimizer) is performing the CONVERT() operation on rows that contain string values that can't be converted to DATETIME.

Basically, you do not have control over which rows the optimizer performs that conversion on. You know that you only need that conversion done on certain rows, and you have predicates (WHERE or ON clauses) that exclude those rows (limit the rows to those that need the conversion), but your execution plan is performing the CONVERT() operation on rows BEFORE those rows are excluded.

(For example, the optimizer may be electing to a do a table scan, and performing that conversion on every row, before any predicate is being applied.)

I can't give a specific answer, without a specific question and specific SQL that is generating the error.


One simple approach to addressing the problem would be to use the ISDATE() function to test whether the string value can be converted to a date.

That is, replace:

CONVERT(DATETIME,eav.Value)

with:

CASE WHEN ISDATE(eav.Value) > 0 THEN CONVERT(DATETIME, eav.Value) ELSE NULL END

or:

CONVERT(DATETIME, CASE WHEN ISDATE(eav.Value) > 0 THEN eav.Value ELSE NULL END)

Note that the ISDATE() function is subject to some significant limitations, such as being affected by the DATEFORMAT and LANGUAGE settings of the session.


If there is some other indication on the eav row, you could use some other test, to conditionally perform the conversion.

CASE WHEN eav.ValueIsDateTime=1 THEN CONVERT(DATETIME, eav.Value) ELSE NULL END

The other approach I've used is to try to gain some modicum of control over the order of operations of the optimizer, using inline views or Common Table Expressions, with operations that force the optimizer to materialize them and apply predicates, so that happens BEFORE any conversion in the outer query.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!