Pergunta

We created an indexed view by such sql:

Select Table1_ID, Count_BIG(*) as Table2TotalCount from Table2 inner join
Table1 inner join... where...

Also after creating the view, we set clustered unique index on column Table1_ID.
So View consists of two columns:

Table1_ID
Table2TotalCount

We have two questions:

  1. If we use Count(1) or Count_BIG(1) instead of Count_BIG(*), SQL doesn't allow us to set index on Table1_ID
  2. How can we control the type of second column (Table2TotalCount) - SQL give a long nullable type to this column. But we want to set int not nullable type to this column. After creating View, we can't find any way to change column type. Also t-sql we use for creating view, always return int values to Table2TotalCount.
Foi útil?

Solução

You have to use COUNT_BIG(*). It's one of the restrictions on creating an indexed view:

The SELECT statement in the view cannot contain the following Transact-SQL syntax elements:

  • COUNT (COUNT_BIG(*) is allowed.)

You could create a second view that isn't indexed, that references this first view, and casts the data type of the count column to your desired type (and possibly uses an ISNULL() to prevent the nullable property)

Outras dicas

  1. That's probably because you are counting on an expression instead of a field or *. Using count(1) gives the same result as count(*), i.e. counting the number of records, so there is no reason to use count(1).

  2. Use count instead of count_big to get int instead of bigint (long). (The documentation specifically says that the only difference between them is the return type.) I don't know why the value is nullable as count never returns null, but that might be the same for all aggregates, and probably not possible to control.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top