I am looking for a solution to create a separate text-block (consisting of certain conditions) which I could create just once and later reference it inside a query:
Example:
Re-usable text-block (A1, B1, C1, D1 and G1 are actual column names):
-------------
WHERE
A1 > B1 and
B1 < C1 and
D1 > G1
-------------
and here would be the SELECT command:
SELECT * FROM table 1
---- insert reference to the re-usable text block ---
UNION
SELECT * FROM table 2
---- insert reference to the re-usable text block ---
UNION
SELECT * FROM table 3
---- insert reference to the re-usable text block ---
;
I am using UNION command in between Select statements since I have 30+ tables from which I need to fetch data that corresponds to the same exact criteria defined in this re-usable text bock. If I need to make a change, it will only apply to this re-usable text block.
How can I design this so that I only need to make the change in one place, and not once for each query?
What you need here to solve your problem is a Prepared Statement.
This allows you to create a query you want to run several times, while only changing something minimal, such as a column condition.
In your case, if you want to have a parameterized where clause, you could do something like this:
PREPARE stmnt FROM 'SELECT myColumns FROM myTable WHERE ?';
Then, you can set a variable to match what you want in the where clause, and EXECUTE the statement with the USING keyword:
SET @condition = 'a1 < b1';
EXECUTE stmnt USING @condition;
Note the use of the ?
in the prepared statement. This is the placeholder for where the parameter will go. If you have multiple question marks, you will need to have multiple parameters following USING
and they replace the question marks in the order that you write them.