![]() | |
![]() |
| | Thread Tools | Display Modes |
#1
| |||
| |||
|
#2
| |||
| |||
|
|
Hey folks, I have a variable number of identically structured & similarly named tables |
|
for which I would like to expeditiously execute a UNION ALL in succession. e.g. "SELECT * from (x-2) UNION ALL SELECT * FROM (x-1) UNION ALL SELECT * FROM x UNION ALL" etc... where (x-2), (x-1), x are three such tables. I can pull all the tables I need to create this very large UNION ALL query from INFORMATION_SCHEMA.TABLES, so is there any way to somehow construct a looped stored procedure such that I don't have to manually type in the full UNION ALL query? |
#3
| |||
| |||
|
|
Hey folks, I have a variable number of identically structured & similarly named tables for which I would like to expeditiously execute a UNION ALL in succession. e.g. "SELECT * from (x-2) UNION ALL SELECT * FROM (x-1) UNION ALL SELECT * FROM x UNION ALL" etc... where (x-2), (x-1), x are three such tables. I can pull all the tables I need to create this very large UNION ALL query from INFORMATION_SCHEMA.TABLES, so is there any way to somehow construct a looped stored procedure such that I don't have to manually type in the full UNION ALL query? Thanks, Dave -- ______________________________ Remove "_SPAM" to reply directly. |
#4
| |||
| |||
|
|
I have a variable number of identically structured & similarly named tables Why? |
|
for which I would like to expeditiously execute a UNION ALL in succession. e.g. "SELECT * from (x-2) UNION ALL SELECT * FROM (x-1) UNION ALL SELECT * FROM x UNION ALL" etc... where (x-2), (x-1), x are three such tables. I can pull all the tables I need to create this very large UNION ALL query from INFORMATION_SCHEMA.TABLES, so is there any way to somehow construct a looped stored procedure such that I don't have to manually type in the full UNION ALL query? Create a UNION by querying the INFORMATION_SCHEMA and then cut and paste the result. Put the UNION in a view and query that in your proc. Take a look at the partitioned views topic in Books Online. Better still, consider combining this into a single table unless it's a case of "I'm not allowed to fix my database". |
#5
| |||
| |||
|
|
Insead of trying to perform a union all, maybe a different appear would be better.... 1. Create a temporary table with the structure of your output. 2. create a cursor which will loop through the tablenames that you need to query. 3. use the table name to create a dynamic sql statement (see sp_executesql) that will populate the temporary table with the data that you need to select. 4. after the loop, perform a single select on the temp table. Be warned, the performance of this will be extremely bad. |
#6
| |||
| |||
|
|
This is simply the way the db has been designed. Individual clients access individual tables. |
#7
| |||
| |||
|
![]() |
| Thread Tools | |
| Display Modes | |
| |