如果我的代码中有条件,我有2个条件。如果它符合条件1,它会从某个视图执行选择,这没关系。但是,如果它处于条件编号2下,它将从另一个视图中进行选择,该视图会中断(尽管存在),因为它会引用不再存在的表中的列。如果在SQL中检查条件,即使它不匹配
我的意图是不打扰修复视图(或放弃它),因为我有一个逻辑操纵变量,使其落入引用工作视图的条件下。
然而,似乎SQL验证代码的所有视图,即使它是从不执行一个IF块内,生成错误:
Msg 207, Level 16, State 1, Procedure vtest_table, Line 21
Invalid column name 'name'.
Msg 4413, Level 16, State 1, Line 32
Could not use view or function 'vtest_table' because of binding errors.
实施例:
create database test
create table test_table (
id int identity(1,1),
name varchar(20)
)
go
create view vtest_table
as
select id, name
from test_table
go
-- breaking the view
alter table test_table
drop column name
go
declare @var int
set @var = 2
if (@var = 2) -- it should fall under this condition and execute this block
begin
print 'test'
end
-- however, the view in the select statement in this block is checked, and as the view is broken, it returns the error.
else if (@var = 1)
begin
select * from vtest_table
end
值得注意的是:如果我引用的视图不存在可言,说:
else if (@var = 1)
begin
select * from viewthatdoesntexist
end
它EXECUT适当的。看起来,如果视图存在,SQL只会检查依赖关系。
也许你可以只用'EXEC( 'SELECT * FROM vtest_table')' – JamieD77
这工作,但它确实的唯一途径?没有办法阻止SQL Server验证那些不属于其他IF条件的对象吗? – arcoiro
你为什么不**不想修复破碎的视图? – scsimon