I’ve a “TableOriginal” that I want to “split” into multiple tables, each one with the name of the different values than can be found on “split” column in “tableOriginal“. The name, therefore, must be dynamic (maybe formed by a variable that is the result of a previous query).
TableOriginal:
+----+-------+-------+
| id | split | value |
+----+-------+-------+
| 1 | A | v1 |
| 2 | A | v2 |
| 3 | A | v3 |
| 4 | B | v4 |
| 5 | B | v5 |
| 6 | B | v6 |
| 7 | C | v7 |
| 8 | C | v8 |
| 9 | A | v9 |
| 10 | B | v10 |
| 11 | B | v11 |
| 12 | C | v12 |
+----+-------+-------+
TableSplit_A
+----+-------------+-------+
| id | original_id | value |
+----+-------------+-------+
| 1 | 1 | v1 |
| 2 | 2 | v2 |
| 3 | 3 | v3 |
| 4 | 9 | v9 |
+----+-------------+-------+
TableSplit_B
+----+-------------+-------+
| id | original_id | value |
+----+-------------+-------+
| 1 | 4 | v4 |
| 2 | 5 | v5 |
| 3 | 6 | v6 |
| 4 | 10 | v10 |
| 5 | 11 | v11 |
+----+-------------+-------+
TableSplit_C
+----+-------------+-------+
| id | original_id | value |
+----+-------------+-------+
| 1 | 7 | v7 |
| 2 | 8 | v8 |
| 3 | 12 | v12 |
+----+-------------+-------+
You can probably use VIEW for this. For the dynamic approach see the
TEMPTABLEargument to the VIEW.In the VIEW’s Create query you then use alias for the column name.
In my opinion dynamics in relation should be handled in code and not in procedures on server. Anyways, here’s an example:
Now you can query
TableAas any other table (I skipped theTEMPTABLEin this example).Hope this was related to what you where looking for.
Added to fiddler:
http://sqlfiddle.com/#!2/c4304/1
UPDATE: (based on the comments below)
Personally I work by the STORE-NOP principle 😛 use a database only to STOre-REtrieve-NOt-for-Processing ™, so I would do it in two steps:
Then go through each result and inject the result in a pre-defined query (notice {0} in the string, these will be replaced later – and perhaps different in the language you’re using):
Then run the query for each line in result (pseudo code in VB):
I cannot check right now if these are valid statement, but it’s meant as pseudo code so you can get the idea how you can do this in the language you are using.
You also might want to consider use a IF EXIST/DROP VIEW or a TEMPTABLE in the final query.