473,405 Members | 2,354 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Generating Foreign Key Script

We sometimes get very large databases that we want to cut down to use for
testing.

The information is all related to a central accounts table.

The way I thought of doing this is to grab all the foreign constraints and
turn them into cascade delete constraints, then delete as many accounts as I
want.

After this I will restore the constraints back to their original state.

I am having a problem doing this as I cannot find a way to programatically
get the add constraint foreign key sql.

For example, I can use sysforeignkeys to list all the foreign keys or
ADO.OpenSchema(adSchemaForeignKeys...) but this doesn't give me the actual
SQL to modify.

My idea was to go through the database saying:

alter table (tablename) drop constraint (foreign key)
alter table (tablename) add constraint (foreign key) on delete cascade

delete various accounts and related data

alter table (tablename) drop constraint (foreign key)
alter table (tablename) add constraint (foreign key)

Can anyone assist?

Thanks

Jul 20 '05 #1
1 5242
[posted and mailed, please reply in news]

Jason Madison (ja***********@btinternet.com) writes:
We sometimes get very large databases that we want to cut down to use for
testing.

The information is all related to a central accounts table.

The way I thought of doing this is to grab all the foreign constraints
and turn them into cascade delete constraints, then delete as many
accounts as I want.


Here is some code that I have lying around. It does not exactly do what
you are asking for - it is actually moving the fkeys to refer from a
previous generation a table to a new, but you should be able to work
from it.

It is actually part of a Perl script, which is why all @ are preceded
by \. Just remove these. There are also things that start with $. These
are Perl variables that are set in the beginning of the snippet.
# Determine parameters that depends on the SQL Server version.
if (version_ge($X->{SQL_version}, '7')) {
$vclen = 4000;
$varchar = 'nvarchar';
$maxlen = 127; # Max len for an object name.
$quotef = 'quotename'; # Function to quote a name.
$lenf = 'len'; # Function to get string length.
}
else {
die "The SQL generated by aba_tblfkey2 does not run on SQL 6.5\n";
}

# Stringify table names
$old_table = sql_string($old_table);
$this_table = sql_string($this_table);

$sql = <<SQLEND;
-- Move foreign keys from $old_table to $this_table.
SET NOCOUNT ON

DECLARE \@dummy tinyint,
\@fktbl sysname,
\@fkcol sysname,
\@refcol sysname,
\@keyno smallint,
\@constr sysname,
\@prev_constr sysname,
\@drop $varchar($vclen),
\@add1 $varchar($vclen),
\@add2 $varchar($vclen),
\@tmpname sysname,
\@no smallint,
\@err int

DECLARE sql_fkey_cur INSENSITIVE CURSOR FOR
SELECT k = 1, constr = object_name(constid), fktbl = object_name(fkeyid),
fkcol = col_name(fkeyid, fkey), refcol = col_name(rkeyid, rkey),
keyno
FROM sysforeignkeys
WHERE rkeyid = object_id($old_table)
UNION
SELECT k = 2, NULL, NULL, NULL, NULL, NULL
ORDER BY k, constr, keyno
OPEN sql_fkey_cur

SELECT \@no = 0
WHILE 1 = 1
BEGIN
FETCH sql_fkey_cur INTO \@dummy, \@constr, \@fktbl, \@fkcol, \@refcol,
\@keyno
IF \@\@fetch_status <> 0
BREAK

IF (\@constr <> \@prev_constr OR \@constr IS NULL) AND
\@prev_constr IS NOT NULL
BEGIN
-- Add the new foreign constraint.
PRINT \@add1
PRINT \@add2
EXECUTE(\@add1 + \@add2 + ')')
IF \@\@error <> 0 BREAK

-- Drop the old reference, once the new is in place. If we drop first,
-- and something goes wrong, we would lose information.
PRINT \@drop
EXECUTE(\@drop)
IF \@\@error <> 0 BREAK

-- Rename the new reference to the real name.
EXEC \@err = sp_rename \@tmpname, \@prev_constr
SELECT \@err = coalesce(nullif(\@\@error, 0), \@err)
IF \@err <> 0 BREAK
END

IF \@keyno = 1
BEGIN
-- Set up command to create new reference under a temporary name. Use
-- place holders for the column lists.
SELECT \@tmpname = 'new_' + ltrim(str(\@no))
SELECT \@tmpname = \@tmpname +
substring(\@constr, 1, $maxlen - $lenf(\@tmpname))
SELECT \@no = \@no + 1
SELECT \@add1 = 'ALTER TABLE ' + $quotef(\@fktbl) +
' ADD CONSTRAINT ' + $quotef(\@tmpname) +
' FOREIGN KEY (' + $quotef(\@fkcol),
\@add2 = ') REFERENCES ' + $quotef($this_table) + '(' +
$quotef(\@refcol)

-- And set up command to drop current constraint.
SELECT \@drop = 'ALTER TABLE ' + $quotef(\@fktbl) +
' DROP CONSTRAINT ' + $quotef(\@constr)
END
ELSE
BEGIN
-- Add more columns to \@add command.
SELECT \@add1 = \@add1 + ', ' + $quotef(\@fkcol),
\@add2 = \@add2 + ', ' + $quotef(\@refcol)
END

SELECT \@prev_constr = \@constr
END

DEALLOCATE sql_fkey_cur
SQLEND
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #2

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

Similar topics

0
by: dcp | last post by:
I just installed the 4.1.0-alpha-max-nt version of MySql and have just started playing around with it. My first test was to try to create a couple of tables, one with a foreign key constraint. ...
2
by: geoff | last post by:
The table creation script(at the end of this post) works fine on 4.0.1-alpha-win, but the foreign key constraints fail on 4.0.15-win. I am starting the server with the same command for both...
1
by: Matik | last post by:
Hello, I need to change collation in my database (more databases acctualy). Therefore, I wanted to make a script, which will do it at one more time. I already have a cursor, updating...
3
by: drdeadpan | last post by:
Hi, I was using enterprise manager to generate a script for my DB. I scripted only my tables and views and in Options I picked all the options EXCEPT "script Primary Keys, Foreign Keys and...
4
by: Mark | last post by:
BEGINNER QUESTION I have a table which has a compound primary key consisting of two columns. One of these columns is a foreign key which is generated in another table by an identity. I want...
7
by: Nathan Sokalski | last post by:
I am an ASP.NET developer, and Visual Studio 2005 seems to have stopped declaring the controls that I add in the *.designer.vb files, therefore forcing me to manually add them before I can use them...
1
by: Nathan Sokalski | last post by:
Visual Studio 2005 recently stopped generating the *.designer.vb files for my *.aspx and *.ascx files. I am using Service Pack 1, and do not believe I did anything differently than normal prior to...
1
by: Nathan Sokalski | last post by:
Visual Studio 2005 unexpectedly stopped generating the *.designer.vb files for *.aspx and *.ascx files. After a few days of frustration trying to fix this, I noticed that it had the following...
7
by: alnoir | last post by:
I'm working on this script that grabs a web page from a foreign site, searches it for specific information, and grabs web pages from links on the original page. Once I had it working, I tried it out...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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
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
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...

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.