删除查询给出错误,但同样的条件在select中有效

时间:2017-02-17 09:44:43

标签: sql sql-server

delete from T_SEARCH_TABLES
where TABLE_NAME = 'D_VENDOR'
      and SEARCH_ID in(select distinct htvf.Value
                       from T_RESX_VALUES
                            cross apply dbo.func_split(T_RESX_VALUES.[key],'.') as htvf
                       where T_RESX_VALUES.value like '%Invoices - Activity (%'
                              and htvf.Position = '2'
                              and T_RESX_VALUES.[KEY] like 'SearchName.%'
                      )
      and SEARCH_TABLE_ID not in(select SEARCH_TABLE_ID
                                 from T_SEARCH_COLUMNS
                                );

给出错误:

  

Msg 245,Level 16,State 1,Line 1   将varchar值'SearchName'转换为数据类型int时,转换失败。

但是

select *
from T_SEARCH_TABLES
where TABLE_NAME = 'D_VENDOR'
      and SEARCH_ID in(select distinct htvf.Value
                        from T_RESX_VALUES
                            cross apply dbo.func_split(T_RESX_VALUES.[key],'.') as htvf
                        where T_RESX_VALUES.value like '%Invoices - Activity (%'
                              and htvf.Position = '2'
                              and T_RESX_VALUES.[KEY] like 'SearchName.%'
                       )
      and SEARCH_TABLE_ID not in(select SEARCH_TABLE_ID
                             from T_SEARCH_COLUMNS
                            );

工作正常,问题是什么?

1 个答案:

答案 0 :(得分:2)

您确定在DELETE和SELECT语句中内部WHERE CLAUSE的第一个条件

(T_RESX_VALUES.value like '%Invoices - Activity (%'and htvf.Position = '2')

满足了吗?

让我解释一下

我在我的DB上运行了这两个语句

select * from customers where cust_id = 0 and Cust_Name = 1

select * from customers where cust_id = 816171 and Cust_Name = 1

Cust_Name列的类型为varchar。我的表包含一个ID = 816171且Cust_Name =' Mike'但没有ID = 0的客户。

我得到了以下结果: 第一个查询运行正常,但没有返回任何行

第二个查询返回以下错误:

Conversion failed when converting the varchar value 'Mike' to data type int.

如果不满足第一个条件,似乎sql-server甚至不尝试提交转换。

实际上,原因是SQL并不总是以相同的顺序执行where子句的检查,引擎本身每次都会选择最优化的顺序。

你可以在这里阅读更多: http://rusanu.com/2009/09/13/on-sql-server-boolean-operator-short-circuit/

相关问题