开发者

Understanding column type in indexed view in SQL Server 2008 R2

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 h开发者_运维百科ave 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.


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)


  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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜