I have the following problem:
I have an SQL table which contains texts and numbers in one column. I created two views to handle the texts and the numbers.
If I select the views in whole, they work as expected, but if I add a where statement to the select statement, I get the following error:
Conversion failed when converting the varchar value 'Thomas' to data type int.
Can I somehow tell the server to apply for the inner view’s where statement before the outer select’s one?
Please use the following SQL code for reproducing the error:
create schema tst
go
create table tst.tbl(strValue varchar(10))
insert tst.tbl(strValue)
values ('Thomas'), ('1991'), ('Reto'), ('21'), ('Strub')
go
create view tst.tblStr as
select strValue
from tst.tbl
where isnumeric(strValue)=0
go
create view tst.tblInt as
select cast(strValue as int) intValue
from tst.tbl
where isnumeric(strValue)=1
go
select * from tst.tblStr order by strValue --ok
select * from tst.tblInt order by intValue --ok
go
select * from tst.tblInt where intValue<100 --not ok
go
select * from tst.tbl where isnumeric(strValue)=1 and cast(strValue as int) < 100 --ok
go
drop view tst.tblInt
drop view tst.tblStr
drop table tst.tbl
drop schema tst
Use a “case when” for view tst.tblInt.