473,795 Members | 3,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Drop all foreign keys

What is the quickest way to drop all the foreign keys in a database?
Only FKs, not PKs.

Cheers,
San.

Oct 6 '06 #1
8 11809

shsandeep wrote:
What is the quickest way to drop all the foreign keys in a database?
Only FKs, not PKs.
You'll have to do this with some manual processing.

The following query will give you a list of all foreign key constraints
in the database:

select tabname, constname from syscat.tabconst where type='F';

Then you can issue a "ALTER TABLE <tabnameDROP FOREIGN KEY
<constname>" for each key listed.

Oct 6 '06 #2
me******@yahoo. com wrote:
>
shsandeep wrote:
>What is the quickest way to drop all the foreign keys in a database?
Only FKs, not PKs.

You'll have to do this with some manual processing.

The following query will give you a list of all foreign key constraints
in the database:

select tabname, constname from syscat.tabconst where type='F';

Then you can issue a "ALTER TABLE <tabnameDROP FOREIGN KEY
<constname>" for each key listed.
You could wrap this in a stored procedure and issue automatically execute
the DDL statements inside a loop that goes through the result of your above
query. Then you don't have any manual processing any more.

--
Knut Stolze
DB2 Information Integration Development
IBM Germany
Oct 6 '06 #3
shsandeep wrote:
What is the quickest way to drop all the foreign keys in a database?
Only FKs, not PKs.

Cheers,
San.
I do this routinely for certain types of database maintenance. Here's
my UNIX shell script to do so. It generates a file that contains all of
the alter table statements to drop the FKs on the table. (One word of
caution, make sure you have a a copy of the FK defintions elsewhere in
the case you need to reapply them. The output of db2look can come in
handy here.) You'll have to replace some of the variables with info
pertaining to your database.

Regards,
Evan

############### ############### ############### ########
#!/bin/ksh

outfile=fkdrop. ddl

db2 connect to $yourdb user $youruserid using $yourpasswd

db2 "export to fkgen.dat of del \
select constname, tabschema, tabname, reftabschema, reftabname,
fk_colnames, pk_
colnames \
from syscat.referenc es "

echo "-- Foreign Keys as of $(date)" $outfile

cat fkgen.dat |while read line
do
IFS=","
let i=0
for token in $line
do
arr[$i]=$token
let i=$i+1
done

print "\nALTER TABLE ${arr[1]}.${arr[2]}" >$outfile
print "DROP CONSTRAINT ${arr[0]} ;" >$outfile
done

Oct 6 '06 #4
me******@yahoo. com wrote:
shsandeep wrote:
What is the quickest way to drop all the foreign keys in a database?
Only FKs, not PKs.

You'll have to do this with some manual processing.

The following query will give you a list of all foreign key constraints
in the database:

select tabname, constname from syscat.tabconst where type='F';

Then you can issue a "ALTER TABLE <tabnameDROP FOREIGN KEY
<constname>" for each key listed.
Or:

SELECT 'ALTER TABLE' || tabname || 'DROP FOREIGN KEY' || constname ||
';' FROM SysCat.TabConst WHERE Type='F';

Though, i usually wrap the names so the 128 characters don't push
things off the screen.

SELECT 'ALTER TABLE' || VARCHAR(TabName , 30) || 'DROP FOREIGN KEY' ||
VARCHAR(ConstNa me, 30) || ';' FROM SysCat.TabConst WHERE Type='F';
B.

Oct 6 '06 #5

shsandeep wrote:
What is the quickest way to drop all the foreign keys in a database?
Only FKs, not PKs.

Cheers,
San.
I use a pythonscript with the following sql (it also droppes
alternative keys and check constraints):

[...]
sql = """
select tabname, constname from syscat.tabconst
where tabschema = ? and type <'P'
order by type
"""
c1.execute(sql, (schema))
for row in c1.fetchall():
table = row[0]
const = row[1]
drop = """
alter table %s.%s drop constraint %s
""" % (schema,table,c onst)
try:
c2.execute(drop )
except Exception, DB2.error:
print "Warning: %s" % (DB2.error)
pass
[...]

Oct 6 '06 #6
Brian Tkatch wrote:
me******@yahoo. com wrote:
>shsandeep wrote:
What is the quickest way to drop all the foreign keys in a database?
Only FKs, not PKs.

You'll have to do this with some manual processing.

The following query will give you a list of all foreign key constraints
in the database:

select tabname, constname from syscat.tabconst where type='F';

Then you can issue a "ALTER TABLE <tabnameDROP FOREIGN KEY
<constname>" for each key listed.

Or:

SELECT 'ALTER TABLE' || tabname || 'DROP FOREIGN KEY' || constname ||
';' FROM SysCat.TabConst WHERE Type='F';

Though, i usually wrap the names so the 128 characters don't push
things off the screen.

SELECT 'ALTER TABLE' || VARCHAR(TabName , 30) || 'DROP FOREIGN KEY' ||
VARCHAR(ConstNa me, 30) || ';' FROM SysCat.TabConst WHERE Type='F';
Some spaces are missing. Besides, using RTRIM would be much safer because
it doesn't cause truncation if there are longer table/constraint names.

SELECT 'ALTER TABLE ' || RTRIM(TabName) || ' DROP FOREIGN KEY ' ||
RTRIM(ConstName ) || ';' FROM SysCat.TabConst WHERE Type='F';

--
Knut Stolze
DB2 Information Integration Development
IBM Germany
Oct 6 '06 #7
Thanks to everyone for replying!!

Cheers,
San.

Oct 8 '06 #8
Knut Stolze wrote:
Brian Tkatch wrote:
me******@yahoo. com wrote:
shsandeep wrote:
What is the quickest way to drop all the foreign keys in a database?
Only FKs, not PKs.

You'll have to do this with some manual processing.

The following query will give you a list of all foreign key constraints
in the database:

select tabname, constname from syscat.tabconst where type='F';

Then you can issue a "ALTER TABLE <tabnameDROP FOREIGN KEY
<constname>" for each key listed.
Or:

SELECT 'ALTER TABLE' || tabname || 'DROP FOREIGN KEY' || constname ||
';' FROM SysCat.TabConst WHERE Type='F';

Though, i usually wrap the names so the 128 characters don't push
things off the screen.

SELECT 'ALTER TABLE' || VARCHAR(TabName , 30) || 'DROP FOREIGN KEY' ||
VARCHAR(ConstNa me, 30) || ';' FROM SysCat.TabConst WHERE Type='F';

Some spaces are missing. Besides, using RTRIM would be much safer because
it doesn't cause truncation if there are longer table/constraint names.

SELECT 'ALTER TABLE ' || RTRIM(TabName) || ' DROP FOREIGN KEY ' ||
RTRIM(ConstName ) || ';' FROM SysCat.TabConst WHERE Type='F';

--
Knut Stolze
DB2 Information Integration Development
IBM Germany
Oops,iforgotabo utthosespaces!

RTRIM() is nice, but, if the command are to be copied off the screen,
there will be a lot of white space to sift through. Being the command
generates a warning on truncation, and i do such things manually, i use
VARCHAR() instead, and modify the length as required.

B.

Oct 16 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1735
by: Joy | last post by:
MySQL automatically creates an index for the primary key. Now, I want to drop it before I start inserting a million rows of data. Can I drop it at all? Thanks.
1
25581
by: Sabrina | last post by:
Hi everybody, I need some help in SQL Server. I am looking for a command that will "Drop all user table" in a user database. Can anyone help me? Thank you very much Sabrina
10
42423
by: Bodza Bodza | last post by:
I'm having an argument with an incumbent self-taught programmer that it is OK to use null foreign keys in database design. My take is the whole point of a foreign key is that it's not supposed to be optional, it's very definition is it's a necessary link to the parent table and part of the definition. If it's optional it shouldn't be part of the definition of a table and should be in a linking table instead. Comments?
1
3527
by: Woody Rao | last post by:
I'm trying to drop all indexes and primary keys so that i can rebuild them (from a script created from same database on another server). when i go to the 'generate sql scripts', it has the ability to drop or generate all tables. it also has the ability to generate all keys only. but i cant find a way to drop all of these keys... any ideas?
0
2616
by: Bart | last post by:
Hello Sometimes i need to drop one of my tables. DROP TABLE removes all foreign keys connected with that table. After this i need to recreate FK. It is not easy to find dropped keys, so i have script to create all keys in database (ALTER TABLE ... ). It works good, but when FK exists, it will create another (exacly the same).
0
1418
by: Scott Ribe | last post by:
I've got a problem which I think may be a bug in Postgres, but I wonder if I'm missing something. Two tables, A & B have foreign key relations to each other. A 3rd table C, inherits from A. A stored procedure updates a row in C, adds a row each in B & C. I get an integrity violation. All the foreign keys are deferrable, and the stored procedure is called from within a transaction with constraints deferred. (And the foreign keys do refer to...
2
8632
by: clickon | last post by:
I am using ASP.net 2.0 and trying to take advantage of the updated data editing facilities provided through the SQLDataSource control and the DetailsView control. The data is a record from a customer complaints table and one of the fields on the DetailsView control is called ComplaintType. The field is a template field and in insert mode and edit mode i have used a DropDownList control bound to a set of keys and values in a ComplaintTypes...
1
11012
by: apax999 | last post by:
Kinda new to SQL, using SQL Server 2005. I have some foreign keys in a couple of tables. I need to drop these tables, but can't since I'll get the error: Msg 3726, Level 16, State 1, Line 1 Could not drop object 'Client' because it is referenced by a FOREIGN KEY constraint.
1
1794
jamesd0142
by: jamesd0142 | last post by:
select 'ALTER TABLE ' + primary_table + ' drop CONSTRAINT ' + primary_key_name + ' FOREIGN KEY (' + foreign_column_1 + ')' from sysfkeys order by foreign_table How can I change this code to allow me to drop all primary keys instead of foriegn keys? Is there an equivelant table for the primary keys as this one "sysfkeys " for the forign keys? James
0
10215
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10165
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10001
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9043
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7541
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5437
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4113
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 we have to send another system
2
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.