0

I am using with clause in my function where passing table name as parameter. So want use this table name in the query but giving table doesnot exits.Sample query

with EMP_A as(
select EMPNO, SAL 
from EMP 
where DEPTNO in (select DEPTNO from P_TABLE_NAME))

select * from EMP;
3
  • Firstly, you cannot have dynamic table name in SQL. You need to (ab)use EXECUTE IMMEDIATE in PL/SL. Secondly, your CTE and tablename are different. Your CTE is emp_a, while the table you are referring to is emp. Commented Apr 6, 2015 at 12:08
  • typo error it is emp_a Commented Apr 6, 2015 at 12:09
  • Yes, i have wrote plsql function mentioned in my comments Commented Apr 6, 2015 at 12:10

1 Answer 1

1

In your below posted query:

 With emp_a as ( 
       select empno,sal 
       from emp 
       where deptno in(select     deptno from p_table_name)
    )
    select * from emp; 
  • Firstly, you cannot have dynamic table name in SQL. Object names must be static. You need to (ab)use EXECUTE IMMEDIATE in PL/SQL to make it a dynamic SQL.

  • Secondly, your CTE and tablename are different. Your CTE is emp_a, while the table you are referring to is emp.

  • Thirdly, you use the WITH clause, i.e. subquery factoring when you have to use the subquery multiple times. Therefore, the CTE would act as a temporary taboe to hold the subquery resultset.

See the documentation to learn more about EXECUTE IMMEDIATE.

http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/executeimmediate_statement.htm

UPDATE An example

You could use a string variable to assign the dynamic query.

DECLARE
  p_table_name VARCHAR2(30);
  l_sql     VARCHAR2(32767);
  l_value.  NUMBER;
BEGIN
   p_table_name := 'DEPARTMENT';
   l_sql := 'WITH clause...' || p_table_name || ' with clause contunied';
   EXECUTE IMMEDIATE l_sql INTO l_value;
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks lalit for quick reply.I have wrote here sample code.How to use execute immediate inside the in clause. Please suggest
See the link I posted. You need to build the dynamic SQL. Then execute immediate the literal.
Hi, I have to use with clause but in this with clause i cannot write execute immeidate sql.
Actaul my requirement is to pass the table name from function paramter this should be in the with clause of inner query.So it is giving error that table not exist.
with EMP_A as( select EMPNO, SAL from EMP where DEPTNO in (execute immediate 'select DEPTNO from ' || P_TABLE_NAME)) select * from EMP_A;
|

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.