I need to UNION
the results of the same SELECT
code over two different schemas. (Example below.) But every time I need to change something in the code, I have to change it twice. I've already been bitten for forgetting to make the change in the second SELECT
. Is there a way to abstract the SELECT
statement to some sort of function?
This is a query saved on a .sql file, which I run sometimes. I do not have permissions to create views or functions to the DB.
SELECT a.column_a,
b.column_b,
c.column_c
FROM schema_A.table_a AS a,
schema_A.table_b AS b,
schema_A.table_c AS c
WHERE a.id_b = b.id
AND b.id_c = c.id
AND a.column_a LIKE 'something%'
UNION ALL
SELECT a.column_a,
b.column_b,
c.column_c
FROM schema_B.table_a AS a,
schema_B.table_b AS b,
schema_B.table_c AS c
WHERE a.id_b = b.id
AND b.id_c = c.id
AND a.column_a LIKE 'something%'
I'd like to be able to do something like this:
FUNCTION something(@schema) AS (
SELECT a.column_a,
b.column_b,
c.column_c
FROM @schema.table_a AS a,
@schema.table_b AS b,
@schema.table_c AS c
WHERE a.id_b = b.id
AND b.id_c = c.id
AND a.column_a LIKE 'something%'
)
SELECT something(schema_A)
UNION ALL
SELECT something(schema_B)