Creating delete statements out of insert statements
Hi, I'm running an insert script with lots of columns. Before that script is run I want to run a delete script for those records that match the ones in the insert.
The things is that I have generated all these insert scripts and I do not want to manually create delete statments for all these records (there are many...)
So for an insert into like this:
Insert into ANSWERS(A,B,C,X,Y,Z) values ('Yes',No','No','No',null,'Yes')
I want to create a delete somewhat like this:
Delete from ANSWERS where (A,B,C,X,Y,Z) = ('Yes',No','No','No',null,'Yes')
This way I can simple use a find and replace to do this task. Is there anyway to write a delete statement somewhat like this?
Thanks!
A very unusual request.
the things is that I have generated all these insert scriptsWhy can't you generate a script to delete in a similar manner.
Is there anyway to write a delete statement somewhat like this?something like this may help you but remember that this script will fail when you have columns values as "NULL"
SQL> create table answers(a varchar2(3), b varchar2(3), c varchar2(3), x varchar2(3) , y varchar2(3),
2 z varchar2(3));
Table created.
SQL> Insert into ANSWERS(A,B,C,X,Y,Z) values ('Yes','No','No','No','Yes','Yes');
1 row created.
SQL> select substr(txt, 1, length(txt)-1) || ' from dual)' from (
2 select
3 replace(replace(replace(
4 trim('Insert into ANSWERS(A,B,C,X,Y,Z) values (''Yes'',''No'',''No'',''No'',''Yes'',''Yes'')'),
5 'Insert into', 'Delete From'), '(A', ' where (A'), 'values (', ' in (select ') txt
6 from dual);
SUBSTR(TXT,1,LENGTH(TXT)-1)||'FROMDUAL)'
Delete From ANSWERS where (A,B,C,X,Y,Z) in (select 'Yes','No','No','No','Yes','Yes' from dual)
SQL> Delete From ANSWERS where (A,B,C,X,Y,Z) in (select 'Yes','No','No','No','Yes','Yes' from dual);
1 row deleted.
SQL>
Similar Messages
-
Problems with StoredProcedures that use INSERT/DELETE statements
Hello
I am using Hyperion Intelligence explorer 8.5, and the database source is a MS SQL Server 2000 source connected via ODBC.
I have this problem: when I use, in a Query section, a stored procedure that (in its code) uses only SELECT statements I get the result of the query in the Results section, but when I use a storedprocedure that does some work (and executes INSERT or DELETE or other SQL statements) and ends executing a SELECT statement in order to return data to the caller Hyperion hangs.
I mean: first I select the stored procedure (Query\StoredProcedure... menù, than I start it using the Process command in Hyperion.
If the storedproc contains only SELECT statements I get the results, but if it contains INSERT or DELETE (and the last statement is a SELECT) Hyperion does not return any data and if I try to repeat the Process command I get an error that tells "the connection is busy with results from another hstmt".
Before you ask me if the stored procedure works correctly, I can confirm this because the storedproc was tested and returns the correct data if used with the db manager application.
Any suggestions? Did you ever use (successfully )storedprocedures that process data (by INSERT or DELETE statements) and then return the result with a SELECT statement?
Thank you for your helpHi Chris,
Could you please tell us in which version of IR
Hyperion is not going to support Stored
Procedures....
Regards,
ManmohanManmohan,
Did you even read what I just wrote? This is NOT happening. Stroed Procedures are an important part of the Intelligence Product, Oracle is continuing to enhance and support this functionality. I work for Oracle, I worked for Hyperion, and for Brio before that, so believe me when I tell you this.
Chris (whoever he is) is gving out incorrect information in this regard. His suggestion of the workaround for the original issue is completely accurate, but as I added, it was in issue that has been corrected as of 8.5 Service Pack 2, so even the workaround is not required as long as you've upgraded. (Note that some versions of 9.x also will require the workaround due to the timing of the releases overlapping.)
Thanks.
Larry Johnson -
Hi,
I'm trying to create a state machine which monitors a single channel on a field point. I want to monitor up to 64 channels at a time, each one with different instances of the same VI. The VI itself needs to maintain information mainly through feedback nodes both in its own block diagram and subVIs within.
All instances of this VI will be executing inside a main loop as they do not execute loops of their own as this would create 64 threads on the cFP-2200 we're using which I believe would be too much.
My attempted solution to all of this was to make the Channel Monitoring VI along with all SubVIs reentrant and "pre-allocate" for each instance. This does not seem to help as each VI seems to maintain the state of the one which ran before. Maybe I'm missing a step?
Is there a better way to approach this problem without writing a separate VI for each channel and the maintenance headache that would cause?Hi Ben,
I actually read your document for another puzzle and it worked well, I think largely because it involved subVIs which were meant as separate threads. In that case, I used methods to alter inputs while the VI was "running."
In this case, as you know, my SubVIs are not looping inside, they are instead single calls but they do need to maintain the state at the end of their previous call, adding to the data they're tracking after they are called subsequent times. I tried the "call by reference" to call them each time. Below is a screenshot of the VI used to create the occurances and a SubVI used to execute each occurance, this subVI is embedded inside a while loop which I did not show here:
In running my tests, there still seems to be some data sharing of internal variables and feedback nodes between the SubVIs I'm calling, which I do not want. Am I approaching this in the correct way? Is what I'm trying to do even possible? -
Converting a delete statement using VPD policies and context
Hello,
I'm trying to convert a delete statement in a update statement using VPD policies and context.
+/* Supose the user 'user1' already exists. This is an application user */+
conn user1/pwd
create table user1.test_a (
id number(4),
description varchar2(100),
deleted number(1)
+);+
alter table user1.test_a add constraint test_a_pk primary key (id);
insert into user1.test_a (1, 'abc', 0);
insert into user1.test_a (2, 'def', 0);
commit;
I'd like to convert each physical deletion into a logical deletion: statements like "delete from user1.test_a where id = 1" must be converted into "update user1.test_a set deleted = 1 where id = 1".
I've found the following way: I will create a policy to avoid physical deletion. Additionally, the policy function should update the deletion flag too.
conn user1/pwd
+/* Create context package */+
create or replace package user1.pkg_security_context is
procedure p_set_ctx(
i_test_a_id in user1.test_a.id %type
+);+
end;
+/+
create or replace package body user1.pkg_security_context is
procedure p_set_ctx (
i_test_a_id in user1.test_a.id %type
+) is+
begin
dbms_session.set_context( 'user1_ctx', 'test_a_id', i_test_a_id );
end;
end;
+/+
show errors
+/* Create trigger to set the context before deletion */+
create or replace trigger user1.test_a_bef_trg
before delete on user1.test_a
for each row
declare
pragma autonomous_transaction;
begin
-- only commits the preceding update, not the delete that fired the trigger.
commit;
user1.pkg_security_context.p_set_ctx( :old.id );
end;
+/+
show errors
create context user1_ctx using user1.pkg_security_context;
+/* Policy function */+
create or replace function user1.f_policy_chk_dels (
object_schema in varchar2,
object_name in varchar2
+) return varchar2+
is
out_string varchar2(400) default '1=2 ';
+/*+
* out_string is the return value.
* - 'WHERE 1=2' means 'nothing to access'
begin
if ( loc_logged_usr_authorized > 0 ) then
+/*+
* Set the flag deleted to 1
update user1.test_a set deleted = 1 where id = sys_context( 'user1_ctx', 'test_a_id' );
out_string := out_string || 'or 1=1 ';
end if;
return out_string;
end;
+/+
show errors
+/*+
* Create policy
begin
dbms_rls.add_policy(
object_schema => 'user1' ,
object_name => 'test_a' ,
policy_name => 'policy_chk_dels' ,
function_schema => 'user1' , -- function schema
policy_function => 'f_policy_chk_dels' , -- policy function
statement_types => 'DELETE'
+);+
end;
+/+
When I try to delete a record of the table test_a:
conn user1/pwd
SQL> delete from ilogdia.oplsimulaciones sim where sim.id = 9999;
+0 rows deleted+
No rows has been deleted, but the update stmt does not work. That means, the "deleted" flag has not been updated.
Any ideas?
Thank you in advance.
Marco A. Serrano
Edited by: albrotar on Oct 15, 2012 8:42 AM
Edited by: albrotar on Oct 15, 2012 8:42 AM
Edited by: albrotar on Oct 15, 2012 8:43 AMThe policy function is applied once per statement execution. The policy function executes first and the UPDATE statement, presumably, updates no rows because the context is not yet populated. The row-level populates the context (I'm assuming that your session can even see context values populated by an autonomous transaction-- I would guess it could but I'd have to test that) after the UPDATE statement is already complete. The COMMIT in the row-level trigger is also pointless-- it only applies to changes made by the current autonomous transaction, of which there are none-- it cannot apply to changes made in other autonomous transactions. Declaring the row-level trigger to use autonomous transactions doesn't seem to accomplish anything other than to open the question of whether the values set in the context by the autonomous transaction are visible in the caller's transaction.
Even if this, somehow, did work, using autonomous transactions would be a very bad idea since Oracle is free to roll-back a partially executed statement (and the work done by its triggers) and re-execute it. Oracle does that with some regularity to maintain write consistency.
Justin -
Access Code - DELETE Statement with DISTINCTROW and T-SQL
All,
I'm trying to rewrite Access Code to T-SQL Code. I understand how DISTINCTROW works in a SELECT statement but I'm not sure of the same in a DELETE statement.
Any ideas?
DELETE DISTINCTROW Order_detail.*
FROM Order_Master
INNER JOIN Order_detail
ON (Order_Master.OrderID = Order_detail.OrderID)
AND (Order_Master.OrderPartID = Order_detail.OrderPartID)
Thanks,
MSCould we use this syntax to delete records of two tables in same query ?
DELETE DISTINCTROW TableA.*, TableB.* FROM
TableA INNER JOIN TableB ON TableA.Name = TableB.Name
No. You can delete only one table at a time.
If you are using SQL Server 2012, you can try Merge:
create table a (id int, name varchar(10))
insert into a values (1,'aName'), (2,'ABCName'), (3,'BBBName')
create table b(id int, name varchar(10))
insert into b values (1,'bName'), (2,'ABCName'), (3,'BBBName')
declare @t table ( name varchar(10))
Merge a as tgt
using b as src On tgt.name =src.name
When matched then
Delete
Output deleted.name into @t;
delete from b Where name in (select name from @t)
Select * from a
select * from b
drop table a,b -
Caculated column in a Create Table statement
This is my create table statement:
CREATE TABLE DTPartInv
( partinv_partnbr VARCHAR2(10) NOT NULL,
partinv_prodname VARCHAR2(25),
partinv_desc VARCHAR2(25),
partinv_manufact VARCHAR2(25),
partinv_instock INTEGER NOT NULL,
partinv_category VARCHAR2(20),
partinv_purchdate DATE,
partinv_loc VARCHAR2(15),
partinv_price NUMBER(6,2),
partinv_vendor VARCHAR2(20),
partinv_reorder INTEGER NOT NULL,
partinv_serial VARCHAR2(20),
partinv_flag as (case when partinv_instock < partinv_reorder then 'X' else 'O' end), calculated column
CONSTRAINT DTPartInv_partinv_partnbr_pk
PRIMARY KEY (partinv_partnbr)
and these are my Insert into table statements:
INSERT INTO DTPartInv VALUES('XT40010E',Null,'Exhaust Pipe','TMC Inc',2,'Pipes',TO_DATE('11-APR-10','DD-MON-RR'),Null,45.95,'Oracle Auto Parts',1,Null);
INSERT INTO DTPartInv VALUES('CH9260',Null,'Oil Filter','Mechanical Parts',5,'Fuild Filters',TO_DATE('15-Jan-10','DD-MON-RR'),Null,20.00,'Sink Auto P',2,Null);
INSERT INTO DTPartInv VALUES('15W40',Null,'Oil','Sink Oil',20,'Auto Fuilds',TO_DATE('10-Feb-11','DD-MON-RR'),Null,10.00,'Oracle Auto Parts',5,Null,);
INSERT INTO DTPartInv VALUES('C9262',Null,'Fuel Filter','Mechanical Parts',2,'Fuild Filters',TO_DATE('20-Oct-10','DD-MON-RR'),Null,35.95,'Sink Auto Parts',1,Null);
INSERT INTO DTPartInv VALUES('PS7716',Null,'Fuel/Water Separator','Mechanical Parts',4,'Fuild Filters',TO_DATE('09-Dec-10','DD-MON-RR'),Null,50.00,'Sink Auto Parts',1,Null);
INSERT INTO DTPartInv VALUES('800142',Null,'PPI Valve','Beink Pipes Inc',10,'Valves',TO_DATE('01-Jun-11','DD-MON-RR'),Null,20.00,'Oracle Auto Parts',2,Null);
INSERT INTO DTPartInv VALUES('TTS400',Null,'Butt Clamp','Beink Pipes Inc',10,'Valves',TO_DATE('31-Oct-11','DD-MON-RR'),Null,15.95,'Oracle Auto Parts',2,Null);
INSERT INTO DTPartInv VALUES('TBA400',Null,'Lap Clamp','Beink Pipes Inc',10,'Valves',TO_DATE('10-Nov-11','DD-MON-RR'),Null,30.00,'Oracle Auto Parts',2,Null);
INSERT INTO DTPartInv VALUES('SC16650',Null,'Brake pads','CostVB Mechanical',5,'Mechanical Parts',TO_DATE('15-May-11','DD-MON-RR'),Null,60.00,'Adosql Auto Parts',1,Null);
INSERT INTO DTPartInv VALUES('OB46613',Null,'Emergency Door Latch','CostVB Mechanical',3,'Mechanical Parts',TO_DATE('01-Sep-11','DD-MON-RR'),Null,45.95,'Adosql Auto Parts',1,Null);
And this is a sample of the error I'm geeting:
INSERT INTO DTPartInv VALUES('XT40010E',Null,'Exhaust Pipe','TMC Inc',2,'Pipes',TO_DATE('11-APR-10','DD-MON-RR'),Null,45.95,'Oracle Auto Parts',1,Null)
ERROR at line 1:
ORA-00947: not enough values
I need to figure out, what it is that I am missing here. partinv_flag is supposed to be calculated based on partinv_instock and partinv_reorder.You need to name columns:
1 INSERT INTO DTPartInv
2 (partinv_partnbr, partinv_prodname, partinv_desc, partinv_manufact, partinv_instock, partinv_category, partinv_purchdate,
3 partinv_loc, partinv_price, partinv_vendor, partinv_reorder, partinv_serial)
4* VALUES('XT40010E',Null,'Exhaust Pipe','TMC Inc',2,'Pipes',TO_DATE('11-01-10','DD-MM-RR'),Null,45.95,'Oracle Auto Parts',1,Null)
SQL> /
1 row created.
SQL> select * from dtpartinv;
PARTINV_PA PARTINV_PRODNAME PARTINV_DESC
PARTINV_MANUFACT PARTINV_INSTOCK PARTINV_CATEGORY PARTINV_
PARTINV_LOC PARTINV_PRICE PARTINV_VENDOR PARTINV_REORDER
PARTINV_SERIAL P
XT40010E Exhaust Pipe
TMC Inc 2 Pipes 11/01/10
45,95 Oracle Auto Parts 1
OEdited by: P. Forstmann on 21 nov. 2011 18:57
Edited by: P. Forstmann on 21 nov. 2011 19:00 -
i am accessing the local database through JDBC for an application. but i've been getting "not allowed" errors while trying to execute a CREATE TABLE statement in my servlet. It allows all other statements like insert, delete, select etc. i've been using a default table because of the same reason.
so if someone could please throw some light into it.Hi,
Statements like Create which is a Data definition one
will not be entertained by the program while executing.
The reason being the DB cannot allocate the required buffer for crating a table at the time of execution.
So the alterantive is create your DB table manually in ur Db and try other DML statements.
Hope it helps.
Regards,
Guru -
Oracle deadlocks on delete statement
I had a package procedure that deletes from a inline-view. It worked well and didn't create any database locks, looked like this:
PROCEDURE serverdisconnect(pCode1 NUMERIC, pCode2 NUMERIC) IS
BEGIN
DELETE FROM
SELECT cl.* FROM CurrentLogins cl, Accounts a
WHERE cl.Code1 = pCode1
AND cl.Code2 = pCode2
AND cl.Code = a.code
AND a.Type = 'lplayer'
ORDER BY a.code
COMMIT;
END serverdisconnect;I slightly changed the procedure to look like following, and deadlocks started to come:
PROCEDURE ServerDisconnect(pCode1 NUMERIC, pCode2 NUMERIC, pChannelServerCode CurrentLogins.ChannelServerCode%TYPE, pDeleteList OUT cursor_type)
IS
vDeleteList sys.ODCINumberList;
BEGIN
DELETE FROM
SELECT cl.* FROM CurrentLogins cl, Accounts a
WHERE cl.Code1 = pCode1
AND cl.Code2 = pCode2
AND cl.Code = a.code
AND cl.ChannelServerCode = pChannelServerCode
AND cl.Code = a.code
AND a.Type = 'lplayer'
) RETURNING Code
BULK COLLECT INTO vDeleteList;
OPEN pDeleteList FOR
SELECT * FROM TABLE(vDeleteList);
COMMIT;
END ServerDisconnect;As you see the main difference in the delete statement is that i removed "ORDER BY"-clause? Can really such data ordering plays a role with dead locking? Does the data records be always ordered with ORDER-BY-clause same way always to avoid deadlock? Why i started to get deadlock after changing the procedure?
I have Oracle 10g.Yes, typo, i fixed initial post now.
Delete will be technically done on table CurrentLogins, using that inline-view.
I will move the Commit to proper place as you suggested.
but still i don't understand why deadlocks started to occure.
Maybe really the answer is having "order by" clause, which solves the deadlocks?
See this link:
http://www.oracle-base.com/articles/misc/Deadlocks.php
>
To resolve the issue, make sure that rows in tables are always locked in the same order.
>
Does it says that i always have to have "order by" sentence included into my delete statement?
Relationships between tables:
alter table CURRENTLOGINS
add constraint FK_CURRENTLOGINS_ACCOUNTS foreign key (CODE)
references ACCOUNTS (CODE);Maybe ORDER-BY really solves deadlocks then, see:
http://www.dbasupport.com/forums/archive/index.php/t-50438.html
>
Add an explicit ORDER BY to the select, and it will probably go away.
>
Edited by: CharlesRoos on Sep 9, 2010 6:05 AM -
I have question about dml mechanism. particularly delete statement
HI,
I have question about dml mechanism. particularly delete statement
I learned that SQL statements deal with each row. For example, SELECT statement insert each record(1 row) which matched with term of WHERE into record pool.
Also I find that UPDATE, INSERT statement insert each record into memory and if that is commited, I/O is generated with disk.
if so, Do DELETE statements deal with each row which is matched with terms WHERE statements? ortherwise with rownum?
I hope that I know the mechanism of DELETE statement?
If the content above which I mentioned is fault, plz point out.
Thank you for reading this contents.Hi,
leave_for wrote:
HI,
I have question about dml mechanism. particularly delete statement
I learned that SQL statements deal with each row. I'm not sure what you mean.
SQL statements deal with sets of rows ; there may be 0, 1, 2, 3 or more rows in the set.
For example, SELECT statement insert each record(1 row) which matched with term of WHERE into record pool.You must mean an INSERT or MERGE statement that includes a query. A plain old SELECT statement doesn't insert anything, or change any table in any way.
Also I find that UPDATE, INSERT statement insert each record into memory and if that is commited, I/O is generated with disk.That's right. All DML involves some I/O. The I/O may be buffered, so that the DML statement might finish before any disk I/O is actually performed.
if so, Do DELETE statements deal with each row which is matched with terms WHERE statements? ortherwise with rownum?
I hope that I know the mechanism of DELETE statement?Sorry; the last couple of lines you wrote are especially confusing.
When you have a DELETE statement that includes a WHERE clause, such as
DELETE emp
WHERE deptno = 20;then the set of rows that will be deleted is the same set of rows for which the condition "deptno = 20" is TRUE. Again, that may be 1 row, but if it is, that's mere coincidence. The number of rows in the set may be 0, or it may be 2 or more.
If ROWNUM is part of the WHERE clause, then ROWNUM will be considered when Oracle decides which rows to delete; if ROWNUM is not part of the WHERE clause, then ROWNUM will play no part in determining which rows are deleted. Remember, as Damorgan mentioned above, ROWNUM is an arbitrary number. There is no built-in order to the rows in any table. -
Can not modify wire in LabVIEW 8.6 create with State Editor
I have a VI created using LabVIEW 8.6 that incorporates a State Editor diagram (not State Chart). After working on the VI for several weeks, I created a new State. Some of the shift registers were pre-wired (first time I have seen this). The wires connecting to the tunnels that connected to the shift-registers could not be modified. Any clues on how enable modifications of these wires.
Blubell,
I have been able to recreate this with LV 8.6 and the SDE ( State Diagram Editor ) with the following:
1- Use the SDE to create a state diagram with several states.
2 - Go the the block diagram and add a shift register to the outer while loop and wire through case statement.
3 - Right click the tunnel on the case statement and select 'Linked Input Tunnel>Create & Wire Unwired Cases'. LV will go ahead and make the connections for you in the other case statements. I guess its a new tool. Unfortunately it is interacting with the SDE when you add another case and won't let you alter the connection for the new case. It is locking this connection just like it locks several other things to the state diagram.
The cure appears to be this:
1 - Open the state diagram and delete the new case/cases.
2 - Go to the block diagram and right click on the problem child tunnel and select 'Linked Input Tunnel>Clear'. Now you should be able to go back to the SDE and add the new states. -
Create procedure statement Hangs in 11g database, doesn't hang in 10.2
I have installed 11g on a windows workstation and created a new database. I then attempted to import a schema from a tried and tested 10.2 database, this hung.
I pinpointed the cause of the hang to a create procedure sstatement within the import file.
I removed the procedure from the 10.2 database, re-exported and imported sucessfully in to the 11g database minus the rogue prrocedure.
I now have a create statement for the procedure thats causing the hangs, and this hangs when I try and run it - it runs fine against my 10.2 database?
I can comment large chunks of the create procedure statment out so I get an anonymous block that runs, and pinpoint the hang down to the inclusion of the the line marked below
(starting FOR UPDATE OF...........).
I cant work out whats going on, I'm no programmer by the way!
Any pointers would be greatly appreciated.
Nick
declare
job_rec job_table%ROWTYPE;
err_msg varchar2(2000);
abort_msg varchar2(2000);
l_ok boolean := TRUE;
l_bat_job varchar2(14) := 's2_novate_RIC';
LINES DELETED FOR PURPOSE OF POSTING CURSOR c_sah IS
SELECT
sah_next,
sah_table_key,
sah_old_status,
sah_new_status,
sah_processed_ind,
sah_processed_date,
sah_processed_time
FROM senatordba.sah_status_audit_history
JOIN (SELECT distinct to_char(spd_next) spd_next
FROM senatordba.spd_std_risk_dets
JOIN senatordba.rso_risk_system_options
ON rso_spd_next = spd_next
AND spd_ric_code = l_ric_code
AND coalesce(l_uw_year, spd_yr) = spd_yr
AND coalesce(l_risk_ref, spd_ref) = spd_ref
ON spd_next = sah_table_key
AND sah_table_code = 'SPD'
AND sah_status_table_code = 'NOV'
AND sah_processed_ind = 'N';
FOR UPDATE OF sah_processed_ind, sah_processed_date, sah_processed_time; <---------if this line is commented out runs OK, if left in, it hangs??
r_sah c_sah%ROWTYPE;
begin
open c_sah;
close c_sah;
end;Hi Nick, no one else has answered so I thought I'd answer my own question, it appears that I was hitting Oracle bug 9294110. had to uninstall 11.2 and install 11.0.7 instead. very annoyed that I wasted ages diagnosing this known problem. The following test should replicate the hang
connect / as sysdba
create user test identified by test default tablespace users temporary tablespace temp;
grant connect, resource to test;
connect test/test
create table a_tab
( col001 number, col002 number, col003 number, col004 number);
create table b_tab( col001 number);
-- the next statement hangs forever
select
a.col002,
a.col003,
a.col004
from
a_tab a
left outer join b_tab
on a.col001 = b_tab.col001
for update of a.col002,
a.col003,
a.col004; -
SQL error msg - The DELETE statement conflicted with the SAME TABLE REFERENCE constraint
Executed as user: ****. The DELETE statement
conflicted with the SAME TABLE REFERENCE constraint "FK_PARENT_TASK_REF".
The conflict occurred in database "****", table "****", column
'PARENT_TASK_ID'. [SQLSTATE 23000] (Error 547) The statement has been
terminated. [SQLSTATE 01000] (Error 3621). The step failed.
Does this error msg indicate the whole script failed to execute or was it just a single step/task that failed ?
What does error msg mean ?
Anyway to prevent this error msg and ensure script runs successfullyHi mdavidh,
This error occurs because the record 'PARENT_TASK_ID' was referenced by 'FK_PARENT_TASK_REF'.
Please refer below codes:
CREATE TABLE MyTable (
ID INT, primary key(ID), -- primary key
ID_Parent INT foreign key(ID_Parent) references MyTable(ID), -- foreign key reference the same table
insert into MyTable(ID,ID_Parent)
values(0,0);
insert into MyTable(ID,ID_Parent)
values(1,0);
insert into MyTable(ID,ID_Parent)
values(2,0);
insert into MyTable(ID,ID_Parent)
values(3,1);
insert into MyTable(ID,ID_Parent)
values(4,3);
insert into MyTable(ID,ID_Parent)
values(5,4);
CREATE TRIGGER MyTrigger
on MyTable
instead of delete
as
set nocount on
update MyTable set ID_Parent = null where ID_Parent in (select ID from deleted)
delete from MyTable where ID in (select ID from deleted)
Now we could delete records.
delete from MyTable where ID_Parent=0
Thanks,
Candy Zhou -
I'm getting an error on a line in the middle of a larger sql script, only in SQL Azure.
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'foouser')
CREATE USER [foouser] FOR LOGIN [foouser] WITH DEFAULT_SCHEMA=[dbo]
GO
Error: "The CREATE USER statement must be the only statement in the batch."
I don't actually understand what 'the only statement in the batch' means.
What is a batch? Is it a SQL file? Is it related to a 'GO' statement or an 'IF' statement? What is the reason for the error? And how do I avoid it?
Thanks,
Tim>IF...ELSE imposes conditions on the execution of a Transact-SQL statement
I understand the general purpose of an If statement. I could let go of our definition of statement counting disagreeing too except that because of the error I'm stuck.
It's less important for Create User but what I am really puzzled over now is a very similar issue how am I supposed to do a safe version of CREATE LOGIN, when I don't know whether a login has been previously created on the server or whether I
am setting up the database on a clean server?
IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = N'foouser')
CREATE LOGIN [foouser] WITH PASSWORD = 'asdfasdf'
GO
If I try and execute this script, it throws the same error as above.
The first unworkable workaround idea is to omit the if statement
CREATE LOGIN [foouser] WITH PASSWORD = 'asdfasdf'
GO
But if the login already exists on the server (because a similar script was already run), then the script throws an error.
The second unworkable workaround idea is to do
DROP LOGIN [foouser]
GO
CREATE LOGIN [foouser] WITH PASSWORD = 'asdfasdf'
GO
Obviously this throws an error in the second block if the login doesn't already exist on the server.
The third workaround idea I have is to go conditional by putting an IF condition around DROP instead of CREATE:
Unfortunately that doesn't work for me either!
"The DROP LOGIN statement must be the only statement in the batch"
(This is despite the fact that 'drop login' is listed on the
supported commands page, not the partially supported page..?! Which disagrees with the notes on
this page.)
Anyway the real question I am interesting in addressing is: is there actually a way to have a 'Create/Delete login
if exists' operation which is SQL-Azure compatible and doesn't throw me error messages (which messes with the sql execution tool I am using)?
If there is no way, I would like to believe it's because it would be a bad idea to do this. But in that case why is it a bad idea?
Tim -
Delete statement that uses a sub-select with the statement in the cursor
Hi all,
How to write write a delete statement that uses a sub-select with the statement in the cursor?
CURSOR excluded_dates IS
SELECT TO_TIMESTAMP(report_parameter_value, in_date_format_mask)
INTO my_current_date_time
FROM report_parameters
WHERE report_parameters.report_parameter_id = in_report_parameter_id
AND report_parameters.report_parameter_group = 'DATE_TIME'
AND report_parameters.report_parameter_name = 'EXCLUDED_DATE';
OPEN excluded_dates;
LOOP
FETCH excluded_dates INTO my_excluded_date;
EXIT WHEN excluded_dates%NOTFOUND;
DELETE FROM edr_rpt_tmp_inclusion_table
WHERE TO_CHAR(date_time, 'mm/dd/yyyy') = TO_CHAR(my_excluded_date, 'mm/dd/yyyy');
END LOOP;
CLOSE excluded_dates;ThanksHi,
In such case I think is better to create a view an perform the delete using it. Example (using HR schema):
Connected to Oracle Database 10g Express Edition Release 10.2.0.1.0
Connected as hr
SQL> create or replace view v_employees as select * from employees where first_name like 'J%';
View created
SQL> select * from v_employees;
EMPLOYEE_ID FIRST_NAME LAST_NAME EMAIL PHONE_NUMBER HIRE_DATE JOB_ID SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID
110 John Chen JCHEN 515.124.4269 28/09/1997 FI_ACCOUNT 8200,00 108 100
112 Jose Manuel Urman JMURMAN 515.124.4469 07/03/1998 FI_ACCOUNT 7800,00 108 100
125 Julia Nayer JNAYER 650.124.1214 16/07/1997 ST_CLERK 3200,00 120 50
127 James Landry JLANDRY 650.124.1334 14/01/1999 ST_CLERK 2400,00 120 50
131 James Marlow JAMRLOW 650.124.7234 16/02/1997 ST_CLERK 2500,00 121 50
133 Jason Mallin JMALLIN 650.127.1934 14/06/1996 ST_CLERK 3300,00 122 50
139 John Seo JSEO 650.121.2019 12/02/1998 ST_CLERK 2700,00 123 50
140 Joshua Patel JPATEL 650.121.1834 06/04/1998 ST_CLERK 2500,00 123 50
145 John Russell JRUSSEL 011.44.1344.429268 01/10/1996 SA_MAN 14000,00 0,40 100 80
156 Janette King JKING 011.44.1345.429268 30/01/1996 SA_REP 10000,00 0,35 146 80
176 Jonathon Taylor JTAYLOR 011.44.1644.429265 24/03/1998 SA_REP 8600,00 0,20 149 80
177 Jack Livingston JLIVINGS 011.44.1644.429264 23/04/1998 SA_REP 8400,00 0,20 149 80
181 Jean Fleaur JFLEAUR 650.507.9877 23/02/1998 SH_CLERK 3100,00 120 50
186 Julia Dellinger JDELLING 650.509.3876 24/06/1998 SH_CLERK 3400,00 121 50
189 Jennifer Dilly JDILLY 650.505.2876 13/08/1997 SH_CLERK 3600,00 122 50
200 Jennifer Whalen JWHALEN 515.123.4444 17/09/1987 AD_ASST 4400,00 101 10
16 rows selected
SQL> delete from v_employees where hire_date >= to_date('01/06/1998', 'dd/mm/yyyy');
2 rows deleted
SQL> regards, -
Looping delete statement where table name is coming from another table
Hi All,
We have to write code to delete records from active tables of WDSO.We have 5 DSO so inspite of writing delete statement for each table we want to put all table names into one table and then loop through it .but we are getting error when we are refering that table field which has active table name.error is :
"dictionary structure or table is either not active or does not exist "
As per my understanding in a delete /select /insert /update statement we need to put table name (whose field we are refering ) it can't be replaced by a variable .
ex: v_table = 'EMPLOYEE' .
DELETE FROMv_table WHERE EMP_NAME = 'ABDC' .
is wrong and it must be like
ex : DELETE FROM EMPLOYEE WHERE EMP_NAME = 'ABDC' .
but we want to make our code dynamic .
Can you please suggest a way so that we can read the table names from another table and delete data based on some selection fom those tables .
I tried variants ,perform etc and even searched FM for the same but not found a solution .Your help will be greatly appreciated .
Thanks in advance .
Regards,
JayaHi,
You can change your statement as follows:
DELETE FROM (v_table) WHERE EMP_NAME = 'ABDC' .
However, I would not recommend this. There is a standard function module RSAN_ODS_DATA_DELETE which allows selective deletion - that should be a safer way to do this. You can
Maybe you are looking for
-
How many devices can I link to my I-cloud/I-match account?
I have an I-cloud and I-match account with all my music on, most of which consists of my own cd's copied onto it. I've just bought my mum an iPod nano 6th generation for her birthday and I want to put some music onto it for her so it's all ready to
-
Reg: MM flow..
Hi Experts. Can any body please tell me the flow of MM...(Flow chart of business flow..) I need this information ASAP..
-
I found errors in the receiving SQL db's logs: SQL Server Scheduled Job 'Status: Failed - Invoked on: 2014-08-12 12:33:48 - Message: The job failed. The Job was invoked by Schedule 9 . The last step to run was step 1 and ERROR : errorCode=-10735487
-
24" can't see wireless network
Out of the box I was able to get online using my wireless network. I then moved the iMac to my desk and transfered files from a G4 desktop using the Migration software. Everything went pretty well and everything seemed to be working fine...EXCEPT the
-
Lately I have been surfing the internet or checking my e-mails and all of a sudden I get Server Hangup. What is causing this.