Sql-server – Add computed column with “IN” syntax

computed-columnindexsql servert-sql

I have a query in SQL Server 2008R2 that I want to run against a computed column that in turn I am going to index – in order to speed things up.

The column is of type int right now.

I cannot get the syntax right.

alter table dbo.tOutput Add StateNew as State IN (0, 10)

I get an error

Incorrect syntax near the keyword 'IN'.

The query, coming from C# entity framework, should then later on use the index and – well – be fast.

The C# seems to be converted to the IN usage, the original is like this:

tOutput.Where(x => (x.State == 0) || (x.State == 10))

The generated SQL reads

.. FROM tOutput WHERE State IN (0, 10) ..

Best Answer

I do not think that you want a computed column here. It looks like what you really need is a filtered index (introduced in SQL Server 2008), using WHERE [State] IN (0, 10) as the filter. Once this index is created, queries that have that same predicate should use this index. Please take a look at:

Just FYI: a computed column is an expression that needs to return a scalar value. State IN (0, 10) is not a scalar expression, which is why you are getting the error. You could modify it to be something like CONVERT(TINYINT, CASE [State] WHEN 0 THEN 1 WHEN 10 THEN 1 ELSE 0 END), but then indexing that will still include all rows. Using a filtered index will only include the matching rows, which will be smaller and faster :-).