如果我的代碼中有條件,我有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