简体   繁体   中英

sql server clustered index on a view

Im trying to create a view out of quite a complex select query and it wont let me put a clustered index on it because i have to use subqueries and some aggregate functions.

I have to get a clustered index on it otherwise the queries that use the view will take forever. Apparently sql server will only store the result set if u meet a stupid amount of criteria.

The base tables for the view are read-only and and only get updated by a bulk import once a day. I can't see why the results can't be cached.

Does anyone know of any way to get sql server to cache the results of a view so they can in turn be queried later?? I dont really want to create another table cos that would snowball into a bunch of changes all over the place.

Thanks in advance.

I think the answer you are looking for is: Don't use a view to do this. Use a table with the fields corresonding to the returned fields form the sql query . Automate the query to populate this table

The short answer is that a clustered index cannot be created, due to the reasons you mention.

When you ask for a way to cache the results of the complicated query, the only other object that SQL Server provides (and will solve your issue) is a table.

If automation is a problem, you should consider creating the view, but only using it as a way to insert into a table, such that you can do a truncate/insert into the table (selecting from the view) immediately after the bulk insert.

If you use SSIS (SQL Server Integration Services) this is a relatively trivial thing to add.

据我所知,在编译执行计划时,SQL Server本质上会将视图的定义复制并粘贴到其编译查询中-只要您能够向基础表中添加索引,就应该可以获得良好的性能。从查询中。

What you are building sounds like a data warehouse, therefore your best option is to manipulate the data once it is in the system. You can build new tables of denormalised (or however else you are modifying it) and index them to allow quick querying.

You can then build views on top of these tables if you need to.

when using aggregates inside a indexed view you need to use COUNT_BIG() instead of COUNT() otherwise the view won't be created

Also if you are not on Enterprise Edition you need to provide the NOEXPAND hint otherwise the optimizer will not use the view

SELECT *
FROM YourView WITH(NOEXPAND)
WHERE ....

Maybe you don't need a view but you just don't have th correct indexes on the tables, can you post the DDL of the tables (including indexes and constraints)

我遇到了同样的问题,最终将子查询本身放在了聚集索引视图中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM