Using truncate table in stored procedure
Hello
I am trying to truncate and repopulate a table in a procedure. I have found that this appears to be impossible. Surely there is some way around this!!
Can anyone help me overcome this problem?
Dean
null
Use the DBMS_SQL package or (in 8i) execute immediate.
Similar Messages
-
Using temporary tables in stored procedures
Suppose that I have created a temporary table in a stored procedure using an "EXECUTE IMMEDIATE" statement. When I compile the procedure, that table is not created yet, so the compiler says that the table does not exist.
What is the way of using temporary tables in stored procedures?It's a good practice to avoid using DDL statements being executed from stored procedures. "Truncate Table" via dynamic SQL from stored procedure is a different story and is useful in DSS environments.
But if you insist on "creating" tables using Dynamic SQL from Stored Procedures then you must also embed your DML statements in Dynamic SQL to avoid compilation errors.
Example:
Create or Replace Procedure Proc_TestDynamicSQL is
Begin
Execute Immediate 'Create table myTable as select * from user_tables' ;
Execute Immediate 'Update myTable set table_name = ''Test'' ' ; --two single quotes before and after the string "Test"
End;
In this case, Oracle wouldn't care about the table references during compilation. -
Sys Tables In Stored Procedure
How can I use Sys Table in Stored Procedure.
I want to use DBA_TAB_COLOUMNS, in stored procedure.
When I used this table in stored procedure I got an error
ORA - 00942 Table or View Does not exists.
Thanks,
AhamedFrom http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_packages.htm#i1006224
>
Note:
To create without errors (to compile the procedure or package successfully) requires the following additional privileges:
The owner of the procedure or package must be explicitly granted the necessary object privileges for all objects referenced within the body of the code.
The owner cannot obtain required privileges through roles.
>
You need to run
grant select on dba_tab_columns to <owner of procedure>; -
Drop and recreate table in stored procedure
Hi all
When creating tables using Transact-SQL scripts, I have always preferred to drop the table if it exists and then create it explicitly using CREATE TABLE. For two reasons:
1) It does not matter if it is the first time the SP is run ie. if I create the table manually in the first instance and just use TRUNCATE TABLE it could fail if the table is deleted
2) I have control over the data types of the table fields
Just recently though I discovered the error that can occur when dropping and creating a table in the same batch (see link below)
Microsoft Website
This causes me a problem when dropping and creating tables in stored procedures, as I understand that a stored procedure is in itself a single batch?
Can I avoid this error in a stored procedure whilst continuing to drop and create tables? Or should I be taking a different approach?
Coding best practice advice would be greatly appreciated.
Thank youThanks Ronen
Please see my second post immediately before your reply.
Given that I need to store the data output in a physical table for use in QlikView, would you suggest truncating the table each time the SP runs? And then having a script that handles both dropping and creating the physical table, and also creating
the SP?
>> QlikView
QlikView is an Israeli company, right?
In any case I am not familiar with QlikView's application, therefore I can only give you general information, based on assumptions regarding the application, and facts regarding the SQL Server.
>> for use in QlikView
I assume that external application use specific database structure (table
structure) and it is change only in rare situations (for example CMS interface might change the tables if and when a module s update/install). In this case there is no need to drop the table and recreate it and TRUNCATE is the solution.
>> would you suggest truncating the table each time the SP runs
I am sorry but i cant recommend on TRUNCATE a table each time you execute SP, without know the exact reason for this logic. It sound to me, at this point of time (with the information that we have), that this
is very bad logic (application architecture). As I wrote above, basing your application on TRUNCATING the table each time mean that you have problems with multi users. Thins about 2 people that try to execute the same SP at almost the same time. Think about
locking in the SQL Server and bad data (one truncate while the other already inserted the new data and get no rows, if there is no locking).
But TRUNCATE is much better in this case probably then DROP and DELETE, since it is faster, and locking will be shorter (hopefully the application use the correct locking). There are other reasons why TRUNCATE is better, and other people already mentioned
most of them, but time in this scenario might be critical.
>> having a script that handles both dropping and creating the physical table, and also creating the SP?
I do not undestand what is this second step. we said that you truncate the table, so why do you need to
dropping and creating the physical table and who
creating the SP?
Are you meaning that the application create the tables and SP?
There are lot of application that during installation create the database structure. is this what you mean?
Ronen Ariely
[Personal Site] [Blog] [Facebook] -
Truncate in a stored procedure or trigger?
hello all,
is it possible to use 'truncate table' in trigger or stored procedure ?
I can do a delete, but when i use truncate table <mytable>, when i compile the trigger, i get an error,
the word 'TABLE' seems forbidden.
thanks for helpHi Laurent,
I tryed to describe the work-around above.
Let me explain in details.
If you want to use 'TRUNCATE TABLE B' comand from a insert trigger on A, you can do the following:
1) create stored procedure which is autonomous
transaction:
create or replace procedure z1
is
pragma autonomous_transaction;
begin
execute immediate 'TRUNCATE TABLE B';
end;
You don't need put there explicit COMMIT -
it will be executed implicitly (autonomous
transactions require commit or rollback before
completon).
2) Create trigger on A for example:
create trigger trr
before insert on A
begin
z1;
end;
After issuing INSERT command for table A, table B
will be truncated.
Consider the following waterstones here:
1) In contrast with the using of DELETE, if you will
do rollback the changes after insertion in A - everything will rollbacked - except for B truncation. It's already
committed in another transaction. You are not able
to rollback the results of TRUNCATE.
2) If you do uncommitted changes in table B before
insertion in A - you will have
'ORA-00054: resource busy and acquire with NOWAIT specified'
exception because you can't truncate table where another
transaction makes changes.
Regards. -
Using Copy statement in Stored procedure
The following statement works in sqlplus session:
copy from comment/password@servername append amcomment_temp using
select * from amcomment
where commentid in(1,2,3,4)
I want to use this in a stored procedure. There is a long datatype in this table. The
procedure will not compile. Have tried execute immediate and compiler rejects this statement also.'COPY' is a SQL*Plus command, not PL/SQL. This is why the PL/SQL compiler throws it out.
-
Using VIEW inside a stored procedure
Hi,
So I have a View designed in one file that validates someone who is authorized.
Then I have a stored procedure to display authorized stationeries created before a given date. Its takes a parameter @CreatedOn.
How can I use VIEW in my stored procedure so I can display all the authorized which are set 1 before a given date?
My VIEW:
ALTER VIEW vw_AuthorizedStationeries AS
SELECT Authorized
FROM dbo.Stationeries
WHERE Authorized = 1
And my stored procedure:
CREATE PROCEDURE usp_stationeries (@CreatedOn datetime)ASBEGINSELECTFROMENDGO
Thanks!Try something like below, You need to replace CreatedDate column with appropriate date column in your table.
1. Alter the view to get the required date:
ALTER VIEW vw_AuthorizedStationeries AS
SELECT Authorized, CreatedDate
FROM dbo.Stationeries
WHERE Authorized = 1
2. Alter SP:
CREATE PROCEDURE usp_stationeries (@CreatedOn datetime)
AS
BEGIN
SELECT Authorized
FROM vw_AuthorizedStationeries
WHERE CreatedDate <= @CreatedOn
END
GO
OR
You can pull required information directly from your table:
CREATE PROCEDURE usp_stationeries (@CreatedOn datetime)
AS
BEGIN
SELECT Authorized
FROM dbo.Stationeries
WHERE CreatedDate <= @CreatedOn and Authorized = 1
END
GO
If this post answers your query, please click "Mark As Answer" or "Vote as Helpful". -
Use database inside a stored procedure
Hi guys, a stupid question: I'm working with several database and sometimes I'm afraid to run an alter or a create something in the wrong database, bear in mind that several database have the same tables. Sometime happens to run a query oin the db A
instead in the db B. So, the question: If I create a procedure like this,
create procedure creatingPillar as
use USA
begin
IF EXISTS (SELECT * FROM sys.objects WHERE object_id =
OBJECT_ID(N'pillarretail') AND type in (N'U'))
DROP TABLE PillarRetail
create table PillarRetail (anid int , ancore varchar(20), period dec(18,6), settlem datetime2,
settlementper int, asf dec(18,6),astlf dec (18,6), tot dec (18,6) )
insert into PillarRetail select anid, ancore, Period, settlem, settlementper,
asf, astlf, tot from createsemipillar2011
insert into PillarRetail select select anid, ancore, Period, settlem, settlementper,
asf, astlf, tot createsemipillar
end
but I'm wondering if is useless to put the use USA in the stored procedure by the moment that I'm creating the procedure in USA. I mean, having the SP in the USA db even if I run the procedure from another db it should run in USA. Just a stupid question
I know but I got this doubt...
ThanksYou may try as below:
create proc as below: (This will create the proc in USA database.
use USA
Go
create procedure dbo.creatingPillar as
begin
IF EXISTS (SELECT * FROM sys.objects WHERE object_id =
OBJECT_ID(N'pillarretail') AND type in (N'U'))
DROP TABLE PillarRetail
create table PillarRetail (anid int , ancore varchar(20), period dec(18,6), settlem datetime2,
settlementper int, asf dec(18,6),astlf dec (18,6), tot dec (18,6) )
insert into PillarRetail select anid, ancore, Period, settlem, settlementper,
asf, astlf, tot from createsemipillar2011
insert into PillarRetail select select anid, ancore, Period, settlem, settlementper,
asf, astlf, tot createsemipillar
end
Then you can call as below:
Exec USA.dbo.creatingPillar -
How to use order by in stored procedure base block?
How to use order by in stored procedure base block? I need to change order by dynamically
Use SET_BLOCK_PROPERTY('BLOCK_NAME',ORDER_BY,'COLUMN_NAME1, COLUMN_NAME2');
-
Can rs.last() be used after calling the stored procedure?
Can rs.last() be used after calling the stored procedure? If yes what should be the CURSOR types?
Can rs.last() be used after calling the stored
procedure? If yes what should be the CURSOR types?That would depend on the driver/database.
And as I said in your other post it is far more efficient to count records by just returning a count rather than a complete collection regardless of how you get to the end. -
Using Parameterized Arrays in Stored Procedure
I tried following code to pass array value to stored procedure but its giving error, as I am new to this procedure, please advise what am I missing ?
Best Regards,
Luqman
My code is as below.
CREATE TYPE num_array AS table of number;
create or replace procedure give_me_an_array
( p_array in num_array )
as
begin
for i in 1 .. p_array.count
loop
dbms_output.put_line( p_array(i) );
end loop;
end give_me_an_array;
declare
mdata num_array;
begin
mdata(1) := 1234;
mdata(2) := 10;
give_me_an_array(mdata);
end;Hi Satya,
Now I got it, thanks,
Can you please advise, if I use the same stored procedure for EMP Table and use my array values to retrieve the selected EMPNo
I tried following but I could not succeed.
When I compile the stored procedure, error occurs:
"inconsistent datatypes: expected NUMBER got NUM_ARRAY"
for example:
CREATE TYPE NUM_ARRAY AS TABLE OF NUMBER;
Create or Replace Package TB_Data
Is Type CV_Type Is REF CURSOR;
END TB_DATA;
Create or Replace Stored Procedure give_me_an_array
(CV IN OUT TB_DATA.CV_TYPE,
MEmpNo In Num_Array)
Is
Begin
Open CV for
Select * from EMP
Where Empno in MEmpNo;
End myProc;
declare
mdata num_array:=num_array(7839,7844);
begin
give_me_an_array(mdata);
end;
Best Regards,
Luqman -
Find tables in Stored Procedures
Hi...
Is there a way I can find the names of stored procedures where a certain table is referenced without having to look through all of them? I tried using dba_dependencies, but it did not return any rows even when I knew the table was referenced in two stored procs. No rows were returned. This is the query I issued:
select
referenced_name,
referenced_type
from
dba_dependencies
where
name LIKE '%DATA.GL_Activity_Fact%'
Any ideas? I need to modify all the stored procs which reference this table.
Thanks so much!Assuming DATA is the schema name and GL_ACTIVITY_FACT is the table name
1) You would want to use DBA_DEPENDENCIES to search for objects that reference the table, not for objects that are referenced by the table. So you'd want to search on REFERENCED_NAME and REFERENCED_OWNER, not the other way around.
2) Regardless of how you specify the table in your code, the owner and object name will be stored separately in the data dictionary. And both will be all upper case (unless you happen to have created tables with case sensitive names).
So you probably want
SELECT owner, name, type
FROM dba_dependencies
WHERE referenced_owner = 'DATA'
AND referenced_name = 'GL_ACTIVITY_FACT'
AND referenced_type = 'TABLE'Be aware that if you use dynamic SQL to reference the table, there will be no entries in DBA_DEPENDENCIES for that.
Justin -
Visual Basic, DAO, Temp tables in stored procedures
Client code currently uses DAO with SQLPassthrough option in VB to connect to SQl 6.5 db.
I migrated all stored procedures with default options except Oracle 8i temp tables. For every procedure a package and a procedure was created. We use SQL server temporary tables extensively in a few hundred stored procedures. The ref cursor created refers to the temporary table. While migratiing, Create table statement is commented. How are SQL6.5 equivalent of temp tables handled in Oracle? Is there an alternative to temp tables?
I also migrated to another oracle db using the INOUT type for stored procedures. This time only procedures were created. Can these procedures return a record set in DAO with SQLPAssthrough?
How do you call a procedure using DAO in VB to get recordsets?
What is the best way to migrate to Oracle with minimal client code changes?
Thank you in advance.
Umesh
nullKarthick_Arp wrote:
BluShadow wrote:
I agree with Karthick, there's no need for a temporary table in this situation.
And to add, temporary tables should not be created at runtime, they should be part of the initial design of the database, created once and used as needed. Creating them at runtime is just wrong.The problem is the name oracle has given to GTT. The word Temporary mislead lot of SQL Server developers and they think its something same as the temporary table used in SQL Server :)Yeah, Ingres does something similar to SQL Server too, in that you can create a temporary table (Ingres assigned it a unique name and tells you what it is), and you set an expiry time on it (i.e. set it to expire in 1 days time), and then a background process is supposed to clean up the tables that have expired. Unlike Oracle, they are not session specific, but become visible to all once created.
I think there's room for both types of temporary table, but Oracle's does the job (except when you want to use them from a stateless application front end). -
Inserting to a clob field using cx_Oracle via a stored procedure
Hello,
Does anyone have experience using cx_Oracle to call a stored procedure which inserts to a clob field? I have found examples of doing this via straight SQL but I was hoping it was possible to do this via a stored procedure call. Thanks for any help you can provide.
JasonAnd cursor.callproc('insert_clob_proc', (clob,))
doesn't work for you?
PrzemekYes - I should have been more clear in my original post. The callproc function works until we have a value which is over 32K. At values over 32K, we get an error message "ORA-01460: unimplemented or unreasonable conversion requested". I believe this is because we are sending the value as a string and so we would need to figure out how to send as a CLOB in cx_Oracle? Here is some code to use to test if interested...
Oracle (Oracle Database 10g Release 10.1.0.4.0 - Production):
CREATE TABLE clob_test (CLOB_FIELD CLOB);
CREATE OR REPLACE PROCEDURE ins_clob_test (v_clob_field IN CLOB)
AS
BEGIN
INSERT INTO clob_test (clob_field) VALUES (v_clob_field);
END ins_clob_test;
Python (2.5):
conn = cx_Oracle.connect(xhash['oraclelogin'])
cursor = conn.cursor()
clob_var = 'Some test data' * 10000
cursor.callproc('ins_clob_test',(clob_var,))
conn.commit()
cursor.close()
conn.close()
I should also mention that I am the Oracle developer and not the Python programmer - my knowledge of Python is very limited. I would like the Python programmers to use the procedures (packages) I have created to do their inserts but this situation has caused them to put the SQL directly in their code.
Thanks again for any assistance you can provide.
Jason -
Using Row Type in Stored Procedure
Hi,
I am working on ADF technology wherein I need to call Procedure from javacode.
I am using Jdev 11g version.
I am using Entity Impl to invoke my Stored Procedure which I have used Row Type in it.
This procedure is running Independently using Toad. But I am not able to call it from Java code.
For EX: We will call the Stored Proc from Java code in this way.
String stmt = "begin execute_define_deliverables(?,?,?,?); end;";
st.setInt(1,this.XXXXX.intValue());
if(this.getXXXX()!=null)
st.setString(2,this.getXXXXXX());
else
st.setNull(2,Types.VARCHAR);
Whereas the questionmarks indicates the individual columns.
But My problem is I have used Row Type in my Stored Proc.
Any pointers in this regard will be very helpful.
Regards,
KalyanHi Satya,
Now I got it, thanks,
Can you please advise, if I use the same stored procedure for EMP Table and use my array values to retrieve the selected EMPNo
I tried following but I could not succeed.
When I compile the stored procedure, error occurs:
"inconsistent datatypes: expected NUMBER got NUM_ARRAY"
for example:
CREATE TYPE NUM_ARRAY AS TABLE OF NUMBER;
Create or Replace Package TB_Data
Is Type CV_Type Is REF CURSOR;
END TB_DATA;
Create or Replace Stored Procedure give_me_an_array
(CV IN OUT TB_DATA.CV_TYPE,
MEmpNo In Num_Array)
Is
Begin
Open CV for
Select * from EMP
Where Empno in MEmpNo;
End myProc;
declare
mdata num_array:=num_array(7839,7844);
begin
give_me_an_array(mdata);
end;
Best Regards,
Luqman
Maybe you are looking for
-
Can I move an iPhoto library to another user?
I have currently got two iPhoto libraries on my user account, but would like to move one of them to a new user. Is there any way I can do this without any risk of losing any photos? Thanks.
-
Error in calling RESTful (Biztalk) service , in Browser
Hello all, I have Orchestation which have one Two way port with Two Operation in it one for GetCandidate Details and One for Insert_Candidate, Also have deployed this Orchestration and using WCF-WebHttp (Working with REST) adapter at ReceiveLocation
-
Kernel Panic after 10.4.6 Update
Hi all - my Mini was running great on 10.4.5, installed 10.4.6 per Software Update, got the double reboot per messages and article. On second reboot and since, I now get kernel panics (you need to press the power button in several languages) on boot
-
IPhone 5 battery drain since iOS 8.2 update
hello, my name is Udi, from Israel. i have an iPhone 5 which i purchased in June 2013. since the beginning, i have always kept the battery saving "rules", including correct charging of a lithium ion battery, auto-brightness off, reduce motion on, pus
-
Migration of customer master data
hi guys while uploading the customer master data from legacy to sap r/3 with lsmw if some files are not uploaded, in which transaction code we see that files