0

Is there a way to build a select statement in oracle using values stored in variables? For example can you do this:

 declare 
 tbl_var varchar2(10) := "map_set";

begin
select count(*) from tbl_var;
end;

1 Answer 1

3

Yes there is, using execute immediate:

declare 
 tbl_var varchar2(10) := 'map_set';
 result number;

begin
execute immediate 'select count(*) from '||tbl_var into result; --save result into variable
dbms_output.put_line('Total rows:'||result); --print result
end;

Second way, you can create a function that receives table name as parameter and return the count:

create function get_count(tbl_var varchar2) return number is 

 result number;

begin
execute immediate 'select count(*) from '||tbl_var into result;
return result;
end;

After create the function you can query it like this:

select get_count('map_set') from dual; 
Sign up to request clarification or add additional context in comments.

8 Comments

Maybe I am doing this wrong, but I don't get anything in the Data Grid in Toad. But when I run: select count(*) from map_set; I get a count value returned.
you don't see anything because this is plsql code, datagrid is for sql. If you want to see results, you must use dbms_output.put_line and check DBMS Output in toad. Check edit
Check the second way, this will show result in the grid
Ok great! this certainly works ;) I have a follow up question, don't know if I should open a separate thread for it.
Will 'execute immediate' work for functions as well, I tried it but get an invalid sql statement.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.