Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
spinningtop
Starting Member
29 Posts |
Posted - 2010-12-13 : 10:25:42
|
Hi My question is how to optimize a query by looping through a list of ID's. I have a huge SQL server 2008 table, something like 500 million records. I have a storeID field as a primary key which has been indexed. There are about 500 storeid's (not incremental) and about 1 million records per storeid. If I want to even run a simple select query on all these records it takes forever. My question is how to run a simple query, for example through all the records without it taking so long and slowing the whole system down to a standstill. I thought the best option would be to run separate queries which loop through all the 500 storeID's against a list in another table. Not sure where to start with this though. one method I see is to use temp tables. The simple query I would like to run is below, obviously changing the storeID to the next on the list each time it is run, SELECT storeid, location FROM stores WHERE storeid = '10' and location = 'Manchester' Thanks |
|
|
X002548
Not Just a Number
15586 Posts |
|
|
spinningtop
Starting Member
29 Posts |
Posted - 2010-12-13 : 16:12:15
|
Hi Sorry, I'll try to be clearer. I've posted the first 2 columns of the table below. Lets say I want to count all the records in the table but as you say a query which runs through the whole table at once would take too much resources with such a large table as 500 million records, each distinct storeID has about a million records. So I want to run separate count queries on each storeID like the ones below but loop the queries so they run consecutively one after the other using a list to get the next storeID. At the end the results of each count query are added so I get a grand total for the table. I'm mainly just interested in how to iterate through a table like this . SELECT count(*)FROM storesWHERE storeID = '10'SELECT count(*)FROM storesWHERE storeID = '14'SELECT count(*)FROM storesWHERE storeID = '50' storeID location 10 Manchester10 Manchester10 Manchester14 London14 London14 London50 Birmingham 50 BirminghamCheers |
 |
|
|
|
|
|
|
|