Unfortunately some of the more troubling bugs can be very hard to reproduce succinctly. Here is one that has been troubling me for a little while :
The issue is using indexed views with a calculated column. Indexed views, despite their restrictions, are a very handy addition to SQL Server and materializing views to be hard data can certainly improve performance. So to demonstrate my issue we will need to build a table and create a view on it.
create table myTable
(
Id integer not null,
InView char(1) not null,
SomeData varchar(255) not null
)
go
Create view vwIxView
with schemabinding
as
Select ID,Somedata,left(SomeData,CHARINDEX('x',SomeData)-1) as leftfromx
from dbo.myTable
Where InView ='Y'
If we insert some data into the view with
insert into myTable(Id,InView,SomeData)
select 1,'N','a'
unsurprisingly, if we look to the view then there will be no data in it.
Now lets add an index to the view
create unique clustered index pkvwIxView on vwIxView(Id)
The data is now persisted.
Lets now add some more data ,the same data, in a ever so slightly different way.
declare @id integer,
@inview char(1),
@Somedata char(50)
select @id = 1, @inview = 'N',@Somedata = 'a'
insert into myTable(Id,InView,SomeData)
select @id,@inview,@Somedata
What is the result ?
Huh , well its kind of obvious which “LEFT or SUBSTRING function” has errored, but as inview = ‘N’ why should that piece of code even been executed ? Looking at the estimated plan we can more easily see the flow of events.
The ‘compute scalar’ operation is where the LEFT is being executed. ,That is happening before the filter and as there is no ‘x’ in the ‘SomeData’ column , it is unsurprising that the function is erroring. I have tested this on both 2008r2 and 2012 rc0.
I have raised a connect item here, if you want to upvote it.