Hi All,
I am observing unexpected behavior when using a view. I am getting an unexpected conversion error when I use a WHERE clause. I do not get the error if I omit the WHERE clause. The view is purposely defined to exclude the offending row, so it appears that the WHERE clause is being evaluated against the whole underlying table, even though the view previously excluded the row.
I am running SQL Server 2017 RTM-CU20 Enterprise Edition.
drop table if exists test;
drop view if exists test_view;
go
create table test
(
id integer identity (1,1),
value varchar(10)
);
go
insert into test values ('abc01'),('def02'),('ghi03'),('jklmn');
go
create view test_view as
with cte as (select id, value from test where value not like 'jkl%')
select id, value, n = convert(integer,right(value,2)) from cte ;
go
/** SUCCESS **/
select * from test;
select * from test_view;
go
/** FAILURE **/
select * from test_view where n between 2 and 3;
go
drop table if exists test;
drop view if exists test_view;
The view definition explicitly excludes row 4 (value like 'jkl%').
The select * from test_view properly executes and displays the data. It is only after I use a WHERE clause that the view fails.
All other statements are successful until the final SELECT statement. I don't understand why. Any explanation would be much appreciated.
Thank you!
--Dan