How to create new table and insert using function in plsql? - oracle

I want to create a function in plsql to create table dynamically
Create or replace procedure p_dynamic_table (p_table varchar2,
col_specs varchar2)
as
sql_stmt varchar2 (2000);
begin
sql_stmt := 'CREATE TABLE' || p_table || '(' || col_specs || ')';
EXECUTE IMMEDIATE sql_stmt;
end;

Put a space after TABLE and before the ending single quote.
Then your procedure will "work". It will not be a function, but a procedure. Also, it is a procedure that has no added value so I don't understand why you want to code it.
Best regards,
Stew Ashton

Are you want to create Procedure or Function?
You mentioned Function in Topics header but try to create Procedure (according the mentioned code by you).
If you don't want to create constraints & Indexes then your Procedure is okay without
SQL_STMT := 'CREATE TABLE' || P_TABLE || '(' || COL_SPECS || ')';
you must be put SPACE after 'CREATE TABLE' which is already mentioned in answer of Stew Ashton.
According to what I understood, I tried to mention the solution below.
PROCEDURE
CREATE OR REPLACE PROCEDURE P_DYNAMIC_TABLE (P_TABLE VARCHAR2,
COL_SPECS VARCHAR2)
AS
SQL_STMT VARCHAR2 (2000);
BEGIN
SQL_STMT := 'CREATE TABLE ' || P_TABLE || '(' || COL_SPECS || ')';
EXECUTE IMMEDIATE SQL_STMT;
END P_DYNAMIC_TABLE;
Execute Procedure
EXEC P_DYNAMIC_TABLE('TEST_TBL','COLUMN_1 NUMBER , COLUMN_2 VARCHAR2(100), COLUMN_3 DATE');

You can try this!
create or replace procedure f2
is
begin
execute immediate 'create table &nds_ddl(&c1 &datatype)';
end;
Then execute the procedure f2
i.e
exec f2;
Select * from table_name_you_entered;

Related

Use Input Parameter of procedure to declare %Rowtype record

I am trying to insert the data into a table using Bulk Collect.
Here is the code:
create or replace procedure insert_via_bulk_collect authid current_user
as
lc_status number;
cursor lc_old_tb_data is select * from old_table_name;
type lc_old_tb_type is table of old_table_name%rowtype;
lc_old_tb_row lc_old_tb_type;
begin
open lc_old_tb_data;
loop
fetch lc_old_tb_data bulk collect into lc_old_tb_row;
forall i in 1..lc_old_tb_row.count
insert into new_table_name values lc_old_tb_row(i);
commit;
exit when lc_old_tb_data%notfound;
end loop;
close lc_old_tb_data;
end insert_via_bulk_collect;
It's working for me. But I want to pass the table name dynamically.
like
insert_via_bulk_collect(new_tb_nm varchar2(30), old_tb_name varchar2(30))
But I am not able to use those variables in cursor and declaring the record of OLD_TABLE%rowtype.
Is there a way to do this?
Try below code
CREATE OR REPLACE PROCEDURE INSERT_VIA_BULK_COLLECT
(NEW_TABLE_NAME varchar2, OLD_TABLE_NAME varchar2)
as
l_str varchar2(4000);
begin
l_str := 'declare
CURSOR lc_old_tb_data IS SELECT * FROM ' || OLD_TABLE_NAME || ';
TYPE lc_old_tb_type IS TABLE OF '|| OLD_TABLE_NAME || '%rowtype;
lc_old_tb_row lc_old_tb_type;
begin
Open lc_old_tb_data;
loop
fetch lc_old_tb_data bulk collect into lc_old_tb_row;
FORALL i IN 1..lc_old_tb_row.count
INSERT INTO ' || NEW_TABLE_NAME || ' VALUES lc_old_tb_row(i);
COMMIT;
exit when lc_old_tb_data%notfound;
end loop;
close lc_old_tb_data;
end; ';
dbms_output.put_line (l_str);
EXECUTE IMMEDIATE l_str;
end insert_via_bulk_collect;
You can add Exception handing. Also it is recommended to add limit for fetching of data as below fetch lc_old_tb_data bulk collect into lc_old_tb_row l_size; you can put l_size value as per your requirement.
As mentioned in comments, it is better to use direct insert ... select .... In your case, you can combine this way with execute immediate:
create or replace procedure insert_via_bulk_collect(new_tb_nm varchar2, old_tb_name varchar2) is
begin
execute immediate 'insert into ' || new_tb_nm ||
'(<columns list>) select <columns list> from ' || old_tb_nm;
end;

Execute immediate and missing invalid option

The procedure is for cloning a table. It receives the names of the two tables in parameters, and when called it should clone the table.
CREATE OR REPLACE PROCEDURE CLONE_TABLE(
table_source VARCHAR2,
table_destination VARCHAR2)
is
begin
execute immediate 'create table ' || table_destination || 'as select* from '
|| table_source;
end;
But when i call the procedure, I receive error ORA-00922: Missing or invalid option.
BEGIN
CLONE_TABLE('example','example_new')
END
I don't realise what's the problem and how should I fix it.
Writing dynamic SQL is hard, because what should be compilation errors become runtime errors. It is therefore crucial to develop a cool eye when looking at your own code. You have to be the compiler.
It helps to assemble the statement as a variable first. That way you can display the statement in the case of error, which makes debugging easier.
CREATE OR REPLACE PROCEDURE CLONE_TABLE(
table_source VARCHAR2,
table_destination VARCHAR2)
is
stmt varchar2(32767);
begin
stmt := 'create table ' || table_destination || 'as select* from '
|| table_source;
execute immediate stmt;
exception
when others then
dbms_output.put_line(stmt);
raise;
end;
If you had done that if would have been obvious that you were missing a space in front of the as. So your executed statement was this:
create table example_newas select* from example
The space between select and * is optional, but code looks better with one.
There are only 2 problem and couple of suggestions for your code.
Missing space before as select...
Calling of procedure, use exec or call statements.
Suggestions:
Make sure to do proper error handling (so if a table doesn't exists, or if a table destination already exists, you should get proper return message.
Also separate each keyword with space as other answers suggested, like between select and *. But not doing it will not give you error.
CREATE OR REPLACE PROCEDURE CLONE_TABLE(
table_source VARCHAR2,
table_destination VARCHAR2)
is
begin
execute immediate 'create table ' || table_destination || ' as select* from '
|| table_source;
end;
EXEC CLONE_TABLE('example','example_new')
Use this:
CREATE OR REPLACE PROCEDURE CLONE_TABLE (table_source VARCHAR2,
table_destination VARCHAR2)
IS
v_sql varchar2(1000);
BEGIN
v_sql:= 'create table '
|| table_destination
|| ' as select * from '
|| table_source;
dbms_output.put_line(v_sql);
EXECUTE IMMEDIATE v_sql;
END;
The best way to handle issue like you got is to display first what you are trying to execute immediate. You get to know your fault.
There is should be one space before as select.. and in between select and * near select*....
SQL> CREATE OR REPLACE PROCEDURE CLONE_TABLE(
table_source VARCHAR2,
table_destination VARCHAR2)
is
begin
execute immediate 'create table ' || table_destination || ' as select * from ' || table_source;
end;
/ 2 3 4 5 6 7 8
Procedure created.
SQL> create table example(id number);
Table created.
SQL> exec CLONE_TABLE('example','example_new');
PL/SQL procedure successfully completed.

Dynamic call Store Procedure (execute immediate ) Out parameters Problems

I have problem Dynamic Call Store Procedure
v_sql := 'begin '|| p_procname || '(''test1'','' test2 '',:v_output2); end;';
execute immediate v_sql
using out v_output2 ;
dbms_output.put_line(v_output2 || ' ' );
In here ı can call procedure with execute immediate .
But my problem is dynamic bind variable . This values comes from log table then i parse for execute_immediate procedure
v_sql := 'begin '|| p_procname || '(''test1'','' test2'',:v_output2); end;';
v_sql1:= ||using|| 'out v_output2 ' ;
execute immediate v_sql
v_sql1;
It doesnt work like that . How can i make dynamic variables bind , because i call a lot of procedure and thats procedure has different in and out parameters.
I hope you can understand what problem i have .How can i pass this problems thx
here is simple procedure
create procedure test_proc(p_user varchar2, p_code varchar2, p_error varchar2) is
begin
p_error := p_user || p_code;
end;
calling code for same ..
Declare
v_test_proc varchar2(50) := 'test_proc';
p_user varchar2(50) := 'test_name';
p_code varchar2(50) := 'test_code';
p_error varchar2(100);
v_sql varchar2(2000);
begin
v_sql := 'begin ' || v_test_proc || '( :1 ,:2, :3 ); end;';
execute immediate v_sql
using p_user, p_code, out p_error;
dbms_output.put_line(p_error);
end;

How to assign a table name to a variable and using the same inside immediate execute statement

I am trying to assign table name to a variable and to use the same inside execute immediate statement , please help me with the syntax inside execute statement
scenario is
I am trying to pass a table name as parameter in the procedure and am using them inside execute immediate to write into some other table .
please suggest me the syntax for in parameters and for the execute immediate statement.
My Procedure:
CREATE OR REPLACE PROCEDURE tep
AS
v_sql VARCHAR2(1024) ;
a NUMBER;
b VARCHAR2(30) :='t_stg1_non_silicon_purchace_re';
BEGIN
v_sql := q'[SELECT COUNT(*) FROM b ]';
EXECUTE immediate v_sql INTO a;
DBMS_OUTPUT.PUT_LINE( TO_CHAR(v_sql));
DBMS_OUTPUT.PUT_LINE( TO_CHAR(a));
END;
/
You haven't specified what exactly you want to do with the table name in the execute immediate so see example below of how to "CREATE" a table.
DECLARE
vTableName VARCHAR2(40 CHAR);
vSQL VARCHAR2(1000 CHAR);
BEGIN
vTableName:='MY_TABLE_NAME';
vSQL:='CREATE TABLE ' || vTableName || ' (COL1 NUMBER, COL2 NUMBER)';
EXECUTE IMMEDIATE vSQL;
END;
/
This query may satisfy your requirement. Thanks
CREATE OR REPLACE PROCEDURE tep
AS
v_sql VARCHAR2(1024) ;
a NUMBER;
b VARCHAR2(30) :='t_stg1_non_silicon_purchace_re';
BEGIN
v_sql := 'SELECT COUNT(*) FROM'||' '||b;
EXECUTE immediate v_sql INTO a;
DBMS_OUTPUT.PUT_LINE( TO_CHAR(v_sql));
DBMS_OUTPUT.PUT_LINE( TO_CHAR(a));
END;

Create nested procedure in Oracle 10g

I want to create a nested procedure where in the 1st procedure, I want to create a table dynamically with 2 columns and in the 2nd procedure, I want to insert values into that table.
Below is the code I am trying to use; what am I doing wrong?
CREATE or replace PROCEDURE mytable (tname varchar2)
is
stmt varchar2(1000);
begin
stmt := 'CREATE TABLE '||tname || '(sname varchar2(20) ,sage number (4))';
execute immediate stmt;
end;
create PROCEDURE mytable1 (emp_name varchar2,emp_age number,tname varchar2)
is
stmt1 varchar2(1000);
begin
stmt1 := 'insert into '||tname||' values ('Gaurav' ,27)';
execute immediate stmt1;
end;
There's no need to create a nested procedure here. You can do everything in a single procedure.
Note my use of bind variables in the execute immediate statement
create or replace procedure mytable (
Ptable_name in varchar2
, Pemp_name in varchar2
, Pemp_age in number
) is
begin
execute immediate 'create table ' || Ptable_name
|| ' (sname varchar2(20), sage number (4))';
execute immediate 'insert into ' || Ptable_name
|| ' values (:emp_name, :emp_age)'
using Pemp_name, Pemp_age;
end;
More generally, there's no need to use execute immediate at all; creating tables on the fly is indicative of a poorly designed database. If at all possible do not do this; create the table in advance and have a simple procedure to insert data, should you need it:
create or replace procedure mytable (
, Pemp_name in varchar2
, Pemp_age in number
) is
begin
insert into my_table
values (Pemp_name, Pemp_age);
end;
I would highly recommend reading Oracle's chapter on Guarding Against SQL Injection.
If you really feel like you have to do this as a nested procedure it would look like this; don't forget to call the nested procedure in the main one as the nested procedure isn't visible outside the scope of the first.
create or replace procedure mytable (
Ptable_name in varchar2
, Pemp_name in varchar2
, Pemp_age in number
) is
procedure myvalues (
Pemp_name in varchar2
, Pemp_age in number
) is
begin
execute immediate 'insert into ' || Ptable_name
|| ' values (:emp_name, :emp_age)'
using Pemp_name, Pemp_age;
end;
begin
execute immediate 'create table ' || Ptable_name
|| ' (sname varchar2(20), sage number (4))';
myvalues ( Pemp_name, Pemp_age);
end;
Please see Oracle's documentation on PL/SQL subprograms

Resources