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:
- If we use
Count(1)
orCount_BIG(1)
instead ofCount_BIG(*)
, SQL doesn't allow us to set index on Table1_ID - 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)
That's probably because you are counting on an expression instead of a field or
*
. Usingcount(1)
gives the same result ascount(*)
, i.e. counting the number of records, so there is no reason to usecount(1)
.Use
count
instead ofcount_big
to getint
instead ofbigint
(long). (The documentation specifically says that the only difference between them is the return type.) I don't know why the value is nullable ascount
never returns null, but that might be the same for all aggregates, and probably not possible to control.
精彩评论