I am working on some tables which have temporal based rows and are present in different databases. The idea is to write stored proc to get and finally process the data, which in turn would make use of many joins which will result in huge amount of data. And then I would perform some kind of aggregate logic to get the needed data.
Such a stored might need to use loops etc and would be very slow.
Could I use Views to make a table which would already be a short listed table consisting of only needed rows (obtained from joins and aggregations). I am missing some fundamentals here:
1. Do views get data at runtime only? If they do, how could I use them to increase performance.
2. Could I use indexing to increase the performance for such a view?
3. Are cursors faster than loops? I know I could use some kind of query to avoid the loops – but suppose if I have to use loop, would cursors be a better choice?
Thanks…
Indexed views can improve performance but read Books online on them as there are many many restriction on what kinds of views can be indexed. They can indeed help with aggregation though as long as you can meet the other conditions that an indexed view must meet.Views that call other views can degrade performance greatly, don’t use them.
To improve performance in aggregation if you can’t use indexed views to solve your problem, one strategy is to store the aggregated values in a table that is updated through triggers anytime the underlying data changes. That way the calculation is only done once for each data change rather than repeated many times in select queries. The trigger would have to be carefully written and handle multiple record inserts/updates/deletes. If the aggregation can be slightly out of synch with real time, you can do this is in a job instead of a trigger.
Cursors and loops are rarely needed in application code. Their real use is generally for database admin tasks. To help you understand better methods to use than looping please read this:
http://wiki.lessthandot.com/index.php/Cursors_and_How_to_Avoid_Them