Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Rajesh.

Asked: August 05, 2016 - 3:05 pm UTC

Last updated: August 08, 2016 - 4:16 am UTC

Version: 11G

Viewed 1000+ times

You Asked

Hi Tom,

Please find the below problem statement and kindly provide the solution.

Problem Statement: I have a schema and that schema contains a table T1.
T1 table contains 2 columns i.e. UserId and CityId.

T1
-------------
USERID CITYID
------ ------
101 BLR
104 CTC
103 DEL
104 BLR
105 NSK
101 CTC
103 BLR


I am querying from UI. User has to select the CityId from UI. It may be 2 CityIds or 3 CityIds or more. So I need a query which will take the parameters dynamically and it will give the records.

E.g.:

In the above case suppose user entered the CITYID as BLR and CTC, so It should display both recrods 101 and 104. If user enters BLR only then it should show 3 records i.e. 101,104 and 103.

Main problem is "How to Pass the no. of parameters dynamically" to a sql query?

Thanks & Regards,
Rajesh

and Connor said...

You can use a nested table type for this


SQL> drop table T1 purge;

Table dropped.

SQL>
SQL> create table t1 ( userid int, cityid varchar2(10));

Table created.

SQL>
SQL> insert into t1 values (101 ,'BLR');

1 row created.

SQL> insert into t1 values (104 ,'CTC');

1 row created.

SQL> insert into t1 values (103 ,'DEL');

1 row created.

SQL> insert into t1 values (104 ,'BLR');

1 row created.

SQL> insert into t1 values (105 ,'NSK');

1 row created.

SQL> insert into t1 values (101 ,'CTC');

1 row created.

SQL> insert into t1 values (103 ,'BLR');

1 row created.

SQL>
SQL> create or replace
  2  procedure list_users(p_cities sys.odcivarchar2list) is
  3  begin
  4    for i in (
  5      select *
  6      from   t1
  7      where  cityid in ( select column_value from table(p_cities))
  8      )
  9    loop
 10      dbms_output.put_line(i.userid||','||i.cityid);
 11    end loop;
 12  end;
 13  /

Procedure created.

SQL>
SQL> set serverout on
SQL> exec list_users(sys.odcivarchar2list('BLR'));
103,BLR
104,BLR
101,BLR

PL/SQL procedure successfully completed.

SQL> exec list_users(sys.odcivarchar2list('BLR','DEL'));
103,BLR
104,BLR
101,BLR
103,DEL

PL/SQL procedure successfully completed.

SQL>
SQL>
SQL>



Is this answer out of date? If it is, please let us know via a Comment

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library