473,836 Members | 1,444 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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( adSchemaForeign Keys...) 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 5281
[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($thi s_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(con stid), fktbl = object_name(fke yid),
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_statu s <> 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(\@con str, 1, $maxlen - $lenf(\@tmpname ))
SELECT \@no = \@no + 1
SELECT \@add1 = 'ALTER TABLE ' + $quotef(\@fktbl ) +
' ADD CONSTRAINT ' + $quotef(\@tmpna me) +
' FOREIGN KEY (' + $quotef(\@fkcol ),
\@add2 = ') REFERENCES ' + $quotef($this_t able) + '(' +
$quotef(\@refco l)

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

SELECT \@prev_constr = \@constr
END

DEALLOCATE sql_fkey_cur
SQLEND
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.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
2324
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. I can't seem to figure out how to drop the foreign key constraint, I read through the docs and it says I need to do a 'show create table <table_name>' to get the internally generated foreign key id, but this does not show up when I do the show...
2
3923
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 versions: mysqld-max-nt --console --transaction-isolation=SERIALIZABLE In 4.0.15-win I can extract the following error after I run the table creation script: ERROR 1005: Can't create table '.\ibdata\#sql-a14_3.frm'
1
7599
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 collation on all tables (fields) in database. The problem is, before I will to update the collations, I need to drop all constrains and pk's.
3
2107
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 Constraits " ( which I was going to script seperately ). I noticed that the the generated file still had all FKs and PKs scripted. When I additionally unchecked the "script Full-Text indexes" option, it worked as expected. Any idea why the full-text...
4
4007
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 to be able to generate the other primary key column value automatically when an insert occurs but assume that I cannot use an identity because it would have to be unique for this table.
7
8155
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 in code that I write in the *.aspx.vb and *.ascx.vb files. Why is it no longer automatically declaring the controls? Is there a way to manually force Visual Studio 2005 to regenerate these files? Is there a setting somewhere that could have...
1
2215
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 this happening. Is there anything that could have caused this? Does anyone know of a way to fix it? Thanks. -- Nathan Sokalski njsokalski@hotmail.com http://www.nathansokalski.com/
1
2349
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 Warning in the Error List tab at the bottom of the screen: Generation of designer file failed: The relative virtual path '?/' is not allowed here. C:\Inetpub\wwwroot\CAT_aspnet\worldnews.aspx 0 0 CAT_aspnet
7
1935
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 on the foreign site. However, the information I got back was nonsensical. I'm guessing the code I get back from the web page is written in that foreign language, but when I -> of the same page, it looks like normal html code. Does anyone know...
0
9671
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10599
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
10257
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
9383
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
7793
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
6980
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5651
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...
0
5829
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3116
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.