473,508 Members | 2,249 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Delete cascade with FK

1 New Member
i have 3 table and they have Foreign key constraint.

Table1 pk Quote_id
Table2 pk order_id , Quote_id is foreign key for table 2
Table3 pk shipment_id, order_id is foreign key for table3

now if i delete a row in table 1 i want to delete cascade on teh row connected with foreign key constraints in the other tables.
Mar 7 '12 #1
2 14548
rski
700 Recognized Expert Contributor
Use ON DELETE CASCADE when you define foreign key.

See here
http://www.postgresql.org/docs/9.1/s...eatetable.html
Mar 8 '12 #2
collinph
1 New Member
I wrote a (recursive) function to delete any row based on its primary key. I wrote this because I did not want to create my constraints as "on delete cascade". I wanted to be able to delete complex sets of data (as a DBA) but not allow my programmers to be able to cascade delete without thinking through all of the repercussions.


I'm still testing out this function, so there may be bugs in it -- but please don't try it if your DB has multi column primary (and thus foreign) keys. Also, the keys all have to be able to be represented in string form, which could be a bit dicey for primary keys that don't convert well to varchar, but in my case, nearly every PK is an integer, so I don't have much to worry about. I use this function VERY SPARINGLY anyway, I value my data too much to enable the cascading constraints on everything.


Basically this function is passed in the schema, table name, and primary value (in string form), and it will start by finding any foreign keys on that table and makes sure data doesn't exist-- if it does, it recursively calls itsself on the found data. It uses an array of data already marked for deletion to prevent infinite loops. Please test it out and let me know how it works for you. Note: It's a little slow.

I call it like so:

Expand|Select|Wrap|Line Numbers
  1. select delete_cascade('public','my_table','1');

Expand|Select|Wrap|Line Numbers
  1.     create or replace function delete_cascade(p_schema varchar, p_table varchar, p_key varchar, p_recursion varchar[] default null)
  2.      returns integer as $$
  3.     declare
  4.         rx record;
  5.         rd record;
  6.         v_sql varchar;
  7.         v_recursion_key varchar;
  8.         recnum integer;
  9.         v_primary_key varchar;
  10.         v_rows integer;
  11.     begin
  12.         recnum := 0;
  13.         select ccu.column_name into v_primary_key
  14.             from
  15.             information_schema.table_constraints  tc
  16.             join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema
  17.             and tc.constraint_type='PRIMARY KEY'
  18.             and tc.table_name=p_table
  19.             and tc.table_schema=p_schema;
  20.  
  21.         for rx in (
  22.             select kcu.table_name as foreign_table_name, 
  23.             kcu.column_name as foreign_column_name, 
  24.             kcu.table_schema foreign_table_schema,
  25.             kcu2.column_name as foreign_table_primary_key
  26.             from information_schema.constraint_column_usage ccu
  27.             join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema 
  28.             join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema
  29.             join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema
  30.             join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema
  31.             where ccu.table_name=p_table  and ccu.table_schema=p_schema
  32.             and TC.CONSTRAINT_TYPE='FOREIGN KEY'
  33.             and tc2.constraint_type='PRIMARY KEY'
  34.     )
  35.         loop
  36.             v_sql := 'select '||rx.foreign_table_primary_key||' as key from '||rx.foreign_table_schema||'.'||rx.foreign_table_name||'
  37.                 where '||rx.foreign_column_name||'='||quote_literal(p_key)||' for update';
  38.             --raise notice '%',v_sql;
  39.             --found a foreign key, now find the primary keys for any data that exists in any of those tables.
  40.             for rd in execute v_sql
  41.             loop
  42.                 v_recursion_key=rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name||'='||rd.key;
  43.                 if (v_recursion_key = any (p_recursion)) then
  44.                     --raise notice 'Avoiding infinite loop';
  45.                 else
  46.                     --raise notice 'Recursing to %,%',rx.foreign_table_name, rd.key;
  47.                     recnum:= recnum +dallas.delete_cascade(rx.foreign_table_schema::varchar, rx.foreign_table_name::varchar, rd.key::varchar, p_recursion||v_recursion_key);
  48.                 end if;
  49.             end loop;
  50.         end loop;
  51.         begin
  52.         --actually delete original record.
  53.         v_sql := 'delete from '||p_schema||'.'||p_table||' where '||v_primary_key||'='||quote_literal(p_key);
  54.         execute v_sql;
  55.         get diagnostics v_rows= row_count;
  56.         --raise notice 'Deleting %.% %=%',p_schema,p_table,v_primary_key,p_key;
  57.         recnum:= recnum +v_rows;
  58.         exception when others then recnum=0;
  59.         end;
  60.  
  61.         return recnum;
  62.     end;
  63.     $$
  64.     language PLPGSQL;
Sep 30 '13 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

1
8856
by: Andrew DeFaria | last post by:
I created the following .sql file to demonstrate a problem I'm having. According to the manual: If |ON DELETE CASCADE| is specified, and a row in the parent table is deleted, then InnoDB...
0
18799
by: Rob Panosh | last post by:
Hello, If I have table the following table structure: Table Customer ( CustomerId Numeric(10,0) Not Null, ... ) Table CustomerOrders ( CustomerOrderId As Numeric(10,0) Not Null,...
2
11499
by: P.B. via SQLMonster.com | last post by:
I cannot execute my sql to create a table with ON DELETE CASCADE option. Here is my sql: CREATE TABLE Employees (Name Text(10) not null, Age number, CONSTRAINT pkEmployees PRIMARY KEY (Name)); ...
4
33653
by: Jean-Christian Imbeault | last post by:
Currently I have a table defined as such: TAL=# \d internal_keywords Table "public.internal_keywords" Column | Type | Modifiers ---------+---------+----------- keyword | text | not null...
3
3154
by: hilz | last post by:
Hi all I am trying to create a relation between two tables. this is the sql statement in question alter table T1 add constraint relation_T1_to_T2 foreign key (T2_ID) references T2 (ID) on...
14
5761
by: Karl O. Pinc | last post by:
Hi, Thought perhaps some other eyes than mine can tell if I'm doing something wrong here or if there's a bug somewhere. I've never passed a ROWTYPE varaible to a function but I don't see where...
2
3079
by: R.Welz | last post by:
Hello. I want to discuss a problem I have with my database design becourse I feel I cannot decide wheather I am on the right way of doing things. First of all, I am writing a literature and...
2
7644
by: nekiv90 | last post by:
Greetings, I have to delete older policies and its related records in other tables. The deletion from the parent table will trigger the deletion of relevant records from about 30 something...
50
5673
by: bonneylake | last post by:
Hey Everyone, I was wondering if anyone could provide a tutorial or example on how to create a stored procedure that uses delete cascade to delete records from 2 tables? i have seen examples...
2
11299
by: manjuns | last post by:
create table A(a1 varchar(10)) create table B(b1 varchar(10), a1 varchar(10) not null) alter table A add primary key(a1) alter table B ADD CONSTRAINT "a_fkey" foreign key (a1) references A (a1)...
0
7225
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7123
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7383
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7498
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5627
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4707
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3194
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1557
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
766
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.