Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: WITH clause with parameters?

In Oracle SQL Developer, I am using a WITH clause, in this (simplified) way:

WITH
foos AS
    SELECT *
    FROM my_table
    WHERE field = 'foo'
bars AS
    SELECT *
    FROM my_table
    WHERE field = 'bar'
SELECT *
FROM foo
INNER JOIN bar
ON foo.id = bar.id

I would like to be able to factor out the 'foo' and 'bar' strings, so that I can have something like:

WITH
subq(my_arg) AS
    SELECT *
    FROM my_table
    WHERE field = my_arg
SELECT *
FROM subq('foo')
INNER JOIN subq('bar')
ON subq('foo').id = subq('foo').id

Because, foos and bars are actually much bigger than this, and there are nut just two of them, so it is getting a bit hard to maintain.

I know this may be not possible with a WITH clause, but what would be the best solution to avoid writing this subquery multiple times? This may be actually quite simple, but I am quite new to SQL...

Thanks for your help.

like image 382
Catherine Gasnier Avatar asked Oct 09 '14 12:10

Catherine Gasnier


People also ask

Can we pass parameter in with clause?

Solution 1. You can use parameters in a WITH clause just like in a traditional statement. The problem in the example is the IN operator which requires a list of values.

Can we pass parameter to WITH clause in Oracle?

You cannot do this in Oracle.

What is the with clause in SQL?

The WITH clause in SQL was introduced in standard SQL to simplify complex long queries, especially those with JOINs and subqueries. Often interchangeably called CTE or subquery refactoring, a WITH clause defines a temporary data set whose output is available to be referenced in subsequent queries.


1 Answers

You can reuse a WITH expression in the next one. But as far as I know you cannot parametrize it. So may be this could help:

WITH
foosAndbars AS 
    (SELECT *
     FROM [Very complex query] ).
foos AS (
    SELECT *
    FROM foosAndbars 
    WHERE field = 'foo'),
bars AS (
    SELECT *
    FROM foosAndbars 
    WHERE field = 'bar')
SELECT *
FROM foo
INNER JOIN bar
ON foo.id = bar.id
like image 158
borjab Avatar answered Oct 04 '22 06:10

borjab