Pass table name to procedure
hi
Can any one plz suggest me , how to pass
table name (that would be varchar) to a procedure,such that i
should be able to do DML and DDL on the table refered !!
EXECUTE IMMEDIATE executes the SQL statement held in a specified
VARCHAR2. So, with a bit of string concatenation, you can make
the statement dynamic, thus:
EXECUTE IMMEDIATE 'DELETE * FROM emp' ;
could become:
EXECUTE IMMEDIATE 'DELETE * FROM '||p_table_name ;
where p_table_name is a VARCHAR2 parameter passed into your
procedure. Check out the PL/SQL User's Guide and Reference,
chapter 10, for full details.
Similar Messages
-
Passing Table Name to Stored Procedure for From Clause
Is it possible to pass a table name to a stored procedure to be used in the From clause? I have the same task to perform with numerous tables and I'd like to use the same SP and just pass the table name in. Something like this:
=======================================
CREATE OR REPLACE PROCEDURE SP_TEST(
in_TABLE IN VARCHAR2,
AS
V_TABLE VARCHAR2(10);
BEGIN
V_TABLE := 'st_' || in_TABLE; -- in_TABLE is 2-3 character string
SELECT some_columns
INTO some_variables
FROM V_TABLE
WHERE some_conditions...;
END;
=======================================
I'm also using the passed table name to assign to variables in the Select and Where clauses. What I'm getting is an error that V_TABLE must be declared. When I hard code the table name, I don't get any errors, even though I'm also using the same method to assign values in the Select and Where clauses.
Thanks,
Ed HollomanYou need to use dynamic SQL whenever you are swapping out object names (tables, columns).
create or replace procedure sp_test
(in_table in varchar2)
is
-- variables
begin
execute immediate 'select a, b, c from st_' || in_table || ' where x = :xval and y = :yval'
into v_a, v_b, v_c using v_x, v_y;
end; -
Passing table name to a procedure and then need to open a cursor ..
Hi All,
I have been out of touch in plsql for sometime and need to do something like :
passing table name to a procedure while calling(fp_table_old captures this value) and then need to open a cursor for this table in 'for i in (select * from fp_table_old )', one of the ways I tried is : for i in (execute immediate Lv_sql_query ) but its not working for me, please find the code below for reference, I know I am sounding stupid but I have been very out of touch, please help.
code :
create procedure p_table_compare(fp_table_old in varchar2, fp_table_new in varchar2)
as
Lv_sql_query varchar2(2000);
begin
Lv_sql_query := 'select * from '||fp_table_old;
for i in (Lv_sql_query)
loop
dbms_output.put_line(i.employee_id);
end loop;
end;
Regards
Rahulif I am doing something like this : for i in (execute immediate Lv_sql_query)
I am getting an error which is :
PLS-00103: Encountered the symbol "IMMEDIATE" when expecting one of the following:
. ( ) , * @ % & | = - + < / > at in is mod remainder not
range rem => .. <an exponent (**)> <> or != or ~= >=
My code:
create or replace procedure p_table_compare(fp_table_old in varchar2, fp_table_new in varchar2)
as
Lv_sql_query varchar2(2000);
begin
--dbms_output.put_line('Hello World');
Lv_sql_query := 'select * from '||fp_table_old;
for i in (execute immediate Lv_sql_query)
loop
dbms_output.put_line(i.employee_id);
end loop;
end;
Please help.
Regards
Rahul -
Pass table name as parameter in prepared Statement
Can I pass table name as parameter in prepared Statement
for example
select * from ? where name =?
when i use setString method for passing parameters this method append single colon before and after of this parameter but table name should be send with out colon as SQL Spec.
I have another way to make sql query in programing but i have a case where i have limitation of that thing so please tell me is it possible with prepared Statment SetXXx methods or not ?
Thanks
Haroon Idrees.haroonob wrote:
I know ? is use for data only my question is this way to pass table name as parameterI assume you mean "how can I do it?" As I have already answered "is this the way?" with no.
Well, I would say (ugly as it is) String concatenation, or stored procedures. -
Passing TABLE NAME as parameter is possible or not?
I want develop a small/simple report like this
TABLE NAME :
WHERE :
ORDER BY :
QUERY ROWS
In the above model i want to pass all the three (TABLE NAME,WHERE and ORDER BY) as a parameter.
My doubt, is that possible to pass TABLE NAME as a parameter? If so!
When i enter any TABLE NAME it has to fetch me out the records of that table (Based on WHERE condition and ORDER BY).
Is that possible to do?
Need some help!
Edited by: Muthukumar Seshadri on Aug 10, 2012 6:19 PMYes, it is possible with lexical parameters. Look in the help for examples:
SELECT Clause
SELECT &P_ENAME NAME, &P_EMPNO ENO, &P_JOB ROLE FROM EMP
P_ENAME, P_EMPNO, and P_JOB can be used to change the columns selected at runtime. For example, you could enter DEPTNO as the value for P_EMPNO on the Runtime Parameter Form.
Note that in this case, you should use aliases for your columns. Otherwise, if you change the columns selected at runtime, the column names in the SELECT list will not match the Report Builder columns and the report will not run.
FROM Clause
SELECT ORDID, TOTAL FROM &ATABLE
ATABLE can be used to change the table from which columns are selected at runtime. For example, you could enter ORD for ATABLE at runtime.
If you dynamically change the table name in this way, you may also want to use lexical references for the SELECT clause (look at the previous example) in case the column names differ between tables.
WHERE Clause
SELECT ORDID, TOTAL FROM ORD WHERE &CUST
ORDER BY Clause
SELECT ORDID, SHIPDATE, ORDERDATE, TOTAL FROM ORD ORDER BY &SORT You have to be really careful with this approach. Dynamic SQL may cause serious performance problems.
Edited by: InoL on Aug 10, 2012 10:06 AM -
Pass table name as a parameter to function
Is there a way to pass table name as a parameter to functions? Then update the table in the function.
Thanks a lot.
JiaxinHi, Harm,
Thank you very much for your suggestion and example. But to get my program work, i need to realise code like follows:
CREATE OR REPLACE FUNCTION delstu_func(stuno char) RETURN NUMBER AS
BEGIN
EXECUTE IMMEDIATE 'DELETE FROM student s' ||
'WHERE' || 's.student_number' || '=' || stuno;
LOOP
DBMS_OUTPUT.PUT_LINE('record deleted');
END LOOP;
END;
SELECT delstu_func('s11') FROM STUDENT;
The intention is to check if such a function can perform operations such as update, delete and insert on occurence of certain values. When executing the above statement, the system returns an error message:
ERROR at line 1:
ORA-00933: SQL command not properly ended
ORA-06512: at "SCMJD1.DELSTU_FUNC", line 3
Could you tell me where is wrong?
Jiaxin -
Pass Datablock name to Procedure
Dear All,
Can I pass datablock name to procedure ? example as below,
PROCEDURE DEADLINE_DATE (DATABLOCK_NAME VARCHAR2) IS
BEGIN
IF DATABLOCK_NAME.TS_DEADLIN_DATE + DATABLOCK_NAME.TS_EXTEND_DAY < DATABLOCK_NAME.TS_TRANS_DATE THEN
MESSAGE ('Deadline date must be greater than transaction date.');
RAISE FORM_TRIGGER_FAILURE;
END IF;
END;
But it will have error when compile module.
Everybody have other solution ??
tks a lot
Borishello,
i have change the code as below : -
IF name_in(':'||DATABLOCK_NAME||'.TS_DEADLIN_DATE')
and the calling code of procedure as below : -
deadlin_date('ABC');
but still receive error ORA-06502.
how to do it ? the procedure of forms must request add ':' before datablock name.
boris -
Help passing table name as parameter to a procedure
Hello,
i'm trying to write a procedure that takes a table name as input and uses a cursor to select a column,count(1) from the passed table to the cursor. The procedure i've come up with is as follows,
CREATE OR REPLACE
PROCEDURE excur(
p_tbl user_tables.table_name%type )
AS
type rc is ref cursor;
c rc;
res BOOLEAN;
BEGIN
open c for 'SELECT columnA,COUNT(1) FROM'|| p_tbl||';';
close c;
END excur;When i try to execute it, an error pops up informing that a table cannot be used in this context. As in i cannot pass a table name as an argument to a procedure. Kindly guide as to how to solve this situation.vishm8 wrote:
Hello,
i'm trying to write a procedure that takes a table name as input and uses a cursor to select a column,count(1) from the passed table to the cursor. The procedure i've come up with is as follows,
CREATE OR REPLACE
PROCEDURE excur(
p_tbl user_tables.table_name%type )
AS
type rc is ref cursor;
c rc;
res BOOLEAN;
BEGIN
open c for 'SELECT columnA,COUNT(1) FROM'|| p_tbl||';';
close c;
END excur;When i try to execute it, an error pops up informing that a table cannot be used in this context. As in i cannot pass a table name as an argument to a procedure. Kindly guide as to how to solve this situation.Generally speaking, Dynamic code is a bad idea for a staggering number of reasons.
That aside, what do you want to return? You're selecting a column and applying an aggregate function (count) but you're not grouping, that doesn't usually work out too well.
TUBBY_TUBBZ?select owner, count(*) from all_objects;
select owner, count(*) from all_objects
ERROR at line 1:
ORA-00937: not a single-group group functionWhy do you perceive the need to be able to take in ANY table name, can't you design an application where table names are known at compile time and not run time? -
Create a procedure which will pass table name as an argument
Please let me know, I want to create a procedure which will take
table name as an argument and will display total no. of rows of
that table.Hopefully this code will help u.
CREATE OR REPLACE PROCEDURE P1(TAB_NAME IN VARCHAR2, ROW_NO
OUT NUMBER)
AS
SQL_STMT VARCHAR2(1000);
BEGIN
SQL_STMT := 'SELECT COUNT(*) FROM ' || TAB_NAME;
EXECUTE IMMEDIATE SQL_STMT INTO ROW_NO;
END;
SQL > VAR A NUMBER
SQL > EXEC P1('EMP',:A);
SQL > PRINT A
A
12
SQL > SELECT COUNT(*) FROM EMP;
COUNT(*)
12 -
Passing table name and columns name as parameters to procedure
i need a procedure that take table name and column names as parameters .
it should display all values in those columns
like
if i execute procedure p ( t1,c1,c2)
it should display c1,c2 values in t1 table
if i execute procedure p ( t1, c1,c2,c3)
it should display c1,c2,c3 values in t1 tables
no of column parameters changesSee if this helps...
First, read the manual on collections.
Second, define your expected results. You want to output the results to the screen? You cannot perform a 'select' in PL/SQL. You will have to select your output into another collection, then loop through that.
Finally, I am curious why this is necessary versus performing a regular query.
Take a look at this incomplete code.
create or replace
package dave_pac
IS
TYPE col_name_list IS VARRAY(20) OF VARCHAR2(30);
PROCEDURE SFA_TAB_COL1
(p_tname IN VARCHAR2
,p_cnames IN col_name_list);
END;
create or replace
package body dave_pac
IS
PROCEDURE SFA_TAB_COL1
(P_tname IN varchar2
,p_cnames in col_name_list)
IS
l_stmt long;
l_rc number;
begin
l_stmt :='select '||p_cnames(1);
for i in 2..p_cnames.count
loop
l_stmt :=l_stmt||' , '||p_cnames(i);
end loop;
l_stmt:= l_stmt||' from '|| p_tname ;
execute immediate l_stmt;
end ;
END dave_pac; -
Passing Table name as parameter to proc.
Hi,
I need to know how to pass a table name to a oracle procedure.
In that procedure I will put that table name in a variable and then I will make operations on that table like DELETE, UPDATE and INSERT.
Kinldy give me the solution for the above problem as soon as possible..
Thanks & regards,
KiranYou shouldn't do it, but if you do, you can use something like this:
Anton
create or replace type my_parm as object
( name varchar2(30)
, val anydata
create or replace type my_parms as table of my_parm
create table t1( c1 number, c2 varchar2(10), c3 date )
create or replace procedure doital( p_action in varchar2, p_tab in varchar2, parms in my_parms )
is
p_stmt1 varchar2(32000);
p_stmt2 varchar2(32000);
ind pls_integer;
curs integer;
dummy integer;
t_a anytype;
t_v varchar2(32000);
t_n number;
t_d date;
begin
curs := dbms_sql.open_cursor;
if upper( p_action ) = 'I'
then
ind := parms.first;
loop
exit when ind is null;
p_stmt1 := p_stmt1 || ', ' || parms( ind ).name;
p_stmt2 := p_stmt2 || ', :b' || to_char( ind );
ind := parms.next( ind );
end loop;
p_stmt1 := 'insert into ' || p_tab || ' (' || substr( p_stmt1, 2 ) || ' ) values (' || substr( p_stmt2, 2 ) || ' )';
dbms_sql.parse( curs, p_stmt1, dbms_sql.native );
ind := parms.first;
loop
exit when ind is null;
case parms( ind ).val.GetType( t_a )
when dbms_types.typecode_varchar2
then
dummy := parms( ind ).val.GetVarchar2( t_v );
dbms_sql.bind_variable( curs, ':b' || to_char( ind ), t_v );
when dbms_types.typecode_number
then
dummy := parms( ind ).val.GetNumber( t_n );
dbms_sql.bind_variable( curs, ':b' || to_char( ind ), t_n );
when dbms_types.typecode_date
then
dummy := parms( ind ).val.GetDate( t_d );
dbms_sql.bind_variable( curs, ':b' || to_char( ind ), t_d );
end case;
ind := parms.next( ind );
end loop;
end if;
dummy := dbms_sql.execute( curs );
dbms_sql.close_cursor( curs );
end;
begin
doital( 'I', 't1', my_parms( my_parm( 'c2', anydata.ConvertVarchar2( 'testje' ) )
, my_parm( 'c1', anydata.ConvertNumber( 3 ) )
, my_parm( 'c3', anydata.ConvertDate( sysdate ) )
doital( 'I', 't1', my_parms( my_parm( 'c1', anydata.ConvertNumber( 77 ) )
, my_parm( 'c2', anydata.ConvertVarchar2( 'goedzo' ) )
, my_parm( 'c3', anydata.ConvertDate( sysdate - 5 ) )
end;
/ -
Passing table names as parameters (aka Trouble building a dynamic SQL command)
I am attempting to develop a template for publishing some data, and would like to pass standard table names as parameters to the various queries. What I have created generates the following error:
Msg 137, Level 16, State 1, Procedure spPublishTrans_FlashersCaution, Line 68
Must declare the scalar variable "@tmpTable".
I thought I was declaring it properly ?
Thanks.
DECLARE @FeatureClass as Nvarchar(MAX) = 'Trans_FlashersCaution'
DECLARE @ED as Nvarchar(MAX) = 'edgis.dbo.' + @FeatureClass
DECLARE @tmpTable TABLE
[OBJECTID] [int] NOT NULL,
[Id] [int] NULL,
[Location] [nvarchar](60) NULL,
[Zone] [nvarchar](5) NULL,
[Shape] [geometry] NULL
DECLARE @tmpTableParam AS NVARCHAR (MAX) = @tmpTable
SELECT @tmpTableParam
DECLARE @execquery AS NVARCHAR(MAX)
SET @execquery = 'INSERT INTO' + @tmpTableParam +
[OBJECTID]
,[Id]
,[Location]
,[Zone]
,[Shape]
SELECT
[OBJECTID]
,[Id]
,[Location]
,[Zone]
,[Shape]
FROM' + @ED;
EXECUTE sp_executesql @execqueryAlways PRINT the SQL string prior to execution when developing dynamic SQL script:
PRINT @execquery
--EXECUTE sp_executesql @execquery
Second step, test the printed SQL script for validity.
Dynamic SQL: http://www.sqlusa.com/bestpractices/dynamicsql/
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014 -
Passing table names through variables
Hi All,
Is it possible to pass the table name in a query using a variable.
For example - can we perform a select on a table where the table name is passed using a variable.
Pl assist. Thanks.Hello,
Are you wanting to do this in a procedure? Say the table name being passed in as Input Parameter?
We can do that using Dynamic SQL:
CREATE PROCEDURE "PROC_01"
(IN v_IN_Var1 NVARCHAR)
LANGUAGE SQLSCRIPT AS
BEGIN
DECLARE ABC NVARCHAR(300) := NULL;
ABC := 'SELECT * FROM ' || :v_IN_Var1;
EXEC (:ABC);
END;
CALL PROC_01 ('DUMMY');
But the only thing is you'll not be able to see the result set directly.
You might wan2 fire the select to insert the data into a different table. -
Passing table name as a parameter
Hi:
I have a question regarding passing part of a table name to crystal. I have table getting created everyday and the dynamic part being Table_<date in yymmdd format>, for e.g. - Table_20140225 for table created on 02/25/2014
I have written query like "select * form Table_{@DT}". This used to work in Crystal 11.5.8.826. but recently we upgraded to 12.2.0.290. In this version of Crystal it is not working and giving me error "com.crystaldecisions.sdk.occa.report.lib.ReportSDKServerException: Missing parameter values.---- Error code:-2147217394 Error code name:missingParameterValueError".
Can you please suggest to get around this problem. Running a stored procedure with REFCURSOR is not an option.
i tried another solution, where i just wrote a stored procedure to do a insert into a table handling the dynamic table in stored procedure. but to my surprise, the stored procedure doesn't execute all the time.
Any help on this is much appreciated...Please see if SP 6 helps. You are on SP 2 at this time.
https://share.sap.com/a:328ro3/MyAttachments/521c18ac-d7fd-4a58-a2dc-9d40d1951975/
- Ludek
Senior Support Engineer AGS Product Support, Global Support Center Canada
Follow us on Twitter -
How to pass Table name as argument in Stored Proc
Hi ,
I have a requirement wherein the table name has to be passed as an argument of SP and the output should be the count from that table based on some filter condition.
Something like this:
create or replace procedure Testing(p_table varchar2,p_count OUT integer) AS
begin
select count(1) into p_count from p_table;
end;
Getting the error on running above code:
PL/SQL: ORA-00942: table or view does not exist
Please let me know how can we do this?
Thanks.Example :SQL> create or replace procedure Testing(
2 p_table varchar2,
3 p_count OUT integer) AS
4 begin
5 execute immediate 'select count(1) from '||p_table
6 into p_count;
7 end;
8 /
Procedure created.
SQL> var n1 number;
SQL> exec Testing('user_objects',:n1);
PL/SQL procedure successfully completed.
SQL> print n1
N1
37
SQL>
Maybe you are looking for
-
How can I get an iPad retina browser to just render native?
I bought a iPad mini retina so that I could work at the same resolution as my 1680x1050 MacBook Pro, but why am I still traped in low res world? Even if I install Atomic Web and change my browser identity to Safari Desktop. It still makes no differen
-
What's a good printer for iMac 10.5.6?
I need a printer for my new iMac. My old printer doesn't work on it. It considers it Classic. Message was edited by: citrine
-
Problems with CS3 and CS4 installations
Hello, I have a problem when I install any product CS3 or CS4. When the program starts establishing, a window appears in the one that says " verifying the profile of the system " but the window being blocked always to 90 %. Does someone know the solu
-
hi. im relatively new to os x and i was wondering if something was possible and if so, how is it done. I like the addition of the chat bubble in the top bar by the clock. however im not sure im liking iChat because i only have a few friends who use A
-
Can I change phone numbers on an iPhone?
I just ordered an iPhone 5 for my wife. I want it for myself, but I'm not eligible yet. My wife is eligible, but she could care less what phone she uses. So can I change the iPhone 5 phone number when I get it so that it is my number instead of he