this is my problem: I want to check rows in a table which name is parameterized, something like table_X
. The value of X comes from another table, so for example in
The only way, without dynamically building queries, is to hard code in every combination and pick out the one you want.
If the table name is a parameter to a stored procedure, this can be in IF blocks. But it feels clunky.
If the fields from each table are the same, you can union the tables together and select from those...
CREATE VIEW myUnifiedStructure AS
SELECT 'Table1' AS tableName, * FROM Table1
UNION SELECT 'Table2' AS tableName, * FROM Table2
UNION SELECT 'Table3' AS tableName, * FROM Table3
-- etc
SELECT * FROM myUnifiedStructure WHERE tableName = 'Table1'
If the fields are different in each table, you may only be interested in a subset of the fields...
CREATE VIEW myUnifiedStructure AS
SELECT 'Table1' AS tableName, field1 AS field1, field4 AS field2 FROM Table1
UNION SELECT 'Table2' AS tableName, field2 AS field1, field3 AS field2 FROM Table2
UNION SELECT 'Table3' AS tableName, field2 AS field1, field4 AS field2 FROM Table3
-- etc
Or you can pass in NULLs for fields that don't exist in the source table...
CREATE VIEW myUnifiedStructure AS
SELECT 'Table1' AS tableName, NULL AS field1, field2 AS field2 FROM Table1
UNION SELECT 'Table2' AS tableName, field1 AS field1, field2 AS field2 FROM Table2
UNION SELECT 'Table3' AS tableName, field1 AS field1, NULL AS field2 FROM Table3
-- etc
Why do you need separate tables like this? It's usually a sign of bad design. Wouldn't it just be easier to create a single table with an identifier field for whichever X` value that record belongs to, that you can join/filter on?
That'd reduce the query to something like
SELECT ...
FROM othertable
JOIN bigtable ON othertable.c_id = bigtable.c_id AND othertable.fieldName = bigtable.fieldName