I have nine different databases representing companies, all on the same SQL server 2008 machine.
In each company database, there is a view called gltrxdet_vw. This is defined across multiple tables, and I can do a
SELECT x, y, z, SUM(amt) AS amt_
FROM gltrxdet_vw
WHERE trxdate BETWEEN '2012-04-01' AND '2012-04-30'
GROUP BY x, y, z
which returns results very quickly due to indexes on the table based on trxdate.
For our consolidated accounts, we need to group across the nine companies so my plan was to create a view which is effectively
CREATE VIEW mcomp_gltrxdet_vw AS
SELECT x, y, z, trxdate, amt
FROM companydb1..gltrxdet_vw
UNION ALL
SELECT x, y, z, trxdate, amt
FROM companydb2..gltrxdet_vw
UNION ALL
...
UNION ALL
SELECT x, y, z, trxdate, amt
FROM companydb9..gltrxdet_vw
So in theory now I can write a query which is
SELECT x, y, z, SUM(amt) AS amt_
FROM mcomp_gltrxdet_vw
WHERE trxdate BETWEEN '2012-04-01' AND '2012-04-30'
GROUP BY x, y, z
x, y and z are fields with transactional info (in reality there will be many more of these and a more complex WHERE condition passed to the query but for the purposes of illustration I hope the above will suffice)
My question is: will SQL Server correctly apply the WHERE condition to the underlying views one at a time before consolidating the results? Or will it be churning for ages building a mega-table before applying the trxdate filter? with very little data in my tables I can’t be sure if this solution will scale correctly. Does it make any difference that I’m querying across different databases?
On a related note, I’m sure some of the responses will be to check the query plans – can anyone link to a decent tutorial of where these tools can be found/how to work them? Been thrown in at the deep end with SSMS (more used to MySQL command line!)
Thanks in advance
Basically, this union-all pattern in views is what’s called (distributed) partitioned views and SQL Server has great support for it. The query optimizer will deal with this just fine.
Anyway, I recommend you look at the execution plan to make sure. I’m adding the link given by Ed Harper in the comments to this answer as it is helpful.