1

I dont know what to search for so I dont know if question has already been answered :-)

I have an Oracle function returning an ID, I want to use this function multiple times in a SQL select statement.

Excample:

select 
    custname,       
    custid,
    salesorderid,
    getIdFromSalesOrder(salesorderid),
    qty,
    getPriceFromID(getIdFromSalesOrder(salesorderid)),
    getXFromID(getIdFromSalesOrder(salesorderid)),
    getYFromID(getIdFromSalesOrder(salesorderid)),
    getZFromID(getIdFromSalesOrder(salesorderid))
from
    tableX,
    tableY
where
    .......

is there any way to use a local variable so I avoid calling getIdFromSalesOrder again and again? Mayby something like this?

id_ number(10,0);

select 
    custname,       
    custid,
    salesorderid,
    getIdFromSalesOrder(salesorderid) into id_,
    qty,
    getPriceFromID(id_),
    getXFromID(id_),
    getYFromID(id_),
    getZFromID(id_)
from
    tableX,
    tableY
where
    .......

SQL select statement will return 3-4.000 rows so in some way the variable will need to be pr. row?

Best regards Anders

1 Answer 1

1

You can use a subquery or CTE:

select custname, custid, salesorderid, id_salesorderid, qty,
       getPriceFromID(id_salesorderid),
       getXFromID(id_salesorderid),
       getYFromID(id_salesorderid),
       getZFromID(id_salesorderid)
from (select x.*, getIdFromSalesOrder(salesorderid) as id_salesorderid
      from tableX x
     ) x join
     tableY y
     on . . .;

Notice that I added table aliases to the query. You should qualify all table names. Also notice that I added in proper, explicit, join syntax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.