(我提前为可怕的解释道歉,但如果你运行下面的查询,你应该明白我的意思!)
为什么MSSQL会在构造true
部分中评估语句if exists
,即使if exists
返回false 也会导致错误?
例如,在下面的两个查询中,第一个检查表是否存在(它确实存在),并检查该表是否具有某些列.出于某种原因,运行此查询会引发以下错误,因为表存在,但列不存在.
Msg 207, Level 16, State 1, Line 21 Invalid column name 'colB'. Msg 207, Level 16, State 1, Line 21 Invalid column name 'colC'. Msg 207, Level 16, State 1, Line 21 Invalid column name 'colA'.
我在这里期望的行为是SQL只是移动到falsepart
构造的构造,而不会抛出错误.(与下一个查询一样).
但是,第二个脚本(相同的条形表名称)成功执行.这是因为查询正在搜索的表不存在.
--Scripts to setup the example. CREATE DATABASE TEST GO USE TEST GO CREATE TABLE t1 (colD VARCHAR(255)) --Create a table with the correct name, but incorrect column names. GO --This query fails, because t1 exists, even though the columns in t1 don't. IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 't1' AND COLUMN_NAME IN ('colA','colB','colC')) BEGIN SELECT colA FROM t1 WHERE colB = 0 AND colC = 1 END ELSE BEGIN SELECT 'FALSE' END GO --This query executes ok, because t2 does not exist. IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 't2' AND COLUMN_NAME IN ('colA','colB','colC')) BEGIN SELECT colA FROM t2 WHERE colB = 0 AND colC = 1 END ELSE BEGIN SELECT 'FALSE' END
当第二个查询运行正常时,是否有人能够向我解释为什么第一个查询错误?
到目前为止,我只是设法在Microsoft SQL Server 2012中测试它.