2017-05-25 133 views
3

如果我的代码中有条件,我有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只会检查依赖关系。

+0

也许你可以只用'EXEC( 'SELECT * FROM vtest_table')' – JamieD77

+0

这工作,但它确实的唯一途径?没有办法阻止SQL Server验证那些不属于其他IF条件的对象吗? – arcoiro

+0

你为什么不**不想修复破碎的视图? – scsimon

回答

1

更新您的观点,因为从表

alter view vtest_table 
as 
select id 
from test_table 
+0

这正是我想要避免做的。 – arcoiro

1

那么SQL你降的名字列是一个说明性语言不是强制性所以有那个......我只是删除参考视图一起或包裹这在TRY/CATCH区块。

begin try 
    exec('select * from vtest_table') 
end try 
begin catch 
    print 'your try failed' 
end catch