【发布时间】:2020-11-04 02:27:13
【问题描述】:
当我尝试更改 SQL where 条件的顺序时,我遇到了错误。
例如:
select *
from dbo.abc
where measure_date <> 'null' and stage = 'xyz'
and measure_place = 'xxx' and fact_code = '123' and std_sis like '%180%'
and cast(measure_date as date) >= '2020/09/01' and cast(measure_date as date) <= '2020/10/13'
在上述查询中,如果我在fact_code 之后保留std_sis,我会得到输出结果,而如果我在查询末尾保留std_sis,例如:
select *
from dbo.abc
where measure_date <> 'null' and stage = 'xyz'
and measure_place = 'xxx' and fact_code = '123'
and cast(measure_date as date) >= '2020/09/01' and cast(measure_date as date) <= '2020/10/13'
and std_sis like '%180%'
我收到如下错误:
消息 241,第 16 级,状态 1,第 1 行
从字符串转换日期和/或时间时转换失败。
【问题讨论】:
-
因此您必须将
measure_date存储为varchar,而不是将其存储为正确的日期。并且您在该列中有一些无效数据。最好的办法是停止使用 varchar 作为日期。下一个最好的事情是纠正无效的。 hack 解决方案是使用 try_convert 并吞下错误。 -
@DaleK 如何通过更改 where 子句顺序来工作?你有什么想法吗?
-
@PoovizhirajanN 它更改了执行计划,并且 SQL Server 发现自己在应用
where子句之前正在处理其他数据。它在 SQL Server 中是一个非常常见的问题,它会访问它最终不需要的数据。 -
@AminGheibi 我的意思不是问题中的问题 - 就像一个人必须处理的事情一样 - 特别是如果一个表包含无效数据。
-
顺便说一下
measure_date <> 'null'与measure_date IS NOT NULL不同-除非您明确/字面上将“null”一词放入字段中(这会导致转换错误,因为它应该是一个日期)我想你想使用 IS NOT NULL 版本。您还应该使用通用日期,例如20200901而不是2020/09/01- 后者在某些设置下可能无法正常工作。
标签: sql sql-server tsql