ritter.vg
tech > code > adventures in code > scary sql
15 Sep 2009 18:23:43 EST

Here's some SQL you should never use.

select  
	cast(  
	' Alter Table [' +  
	src.name +  
	'] Drop Constraint [' +  
	ky.name + ']' +
	char(10) + ' go ' + char(10) +  
	' Alter Table [' +  
	src.name +  
	'] Add Constraint [' +  
	ky.name +  
	'] foreign key ( ['+  
	col_name(src_c.referenced_object_id, src_c.referenced_column_id) +  
	'] ) references ' +  
	refs.name +  
	' ( ['+  
	col_name(refs_c.referenced_object_id, refs_c.referenced_column_id) +  
	'] ) ON DELETE CASCADE ' +  
	char(10) + ' go ' + char(10)  
	as text)  
from sys.foreign_keys ky --key  
inner join sys.objects src --origin  
        on ky.parent_object_id = src.object_id  
inner join sys.objects refs --references  
        on ky.referenced_object_id = refs.object_id  
inner join sys.foreign_key_columns src_c --origin column  
        on ky.object_id = src_c.constraint_object_id  
inner join sys.foreign_key_columns refs_c --reference column  
        on ky.object_id = refs_c.constraint_object_id  

What does it do? Well on SQL Server 2005/8, it will produce a script (output in text mode or the GO's won't work) that will rewrite all your Foreign Keys to cascade deletes. So now, instead of getting a violation when you try delete an item because it has foreign keys, it will silently delete all the data associated with that foreign key. Scary, right?

Notes:

  1. query assumes the FK consists of a 1-to-1 column mapping, no composite columns
  2. you may need to do a little jimmy-ing with the resulting sql to run it nicely
  3. this is silly dangerous. unless you have a damn good reason to do this (like, you don't give a crap about your data and you're setting up a one-off testing enviroment or somesuch) you shouldn't do this.
  4. If the script runs incorrectly, and then you run it again - you will have lost FK's. So be sure to save the very first output of the script to recreate all keys in the event of something going wrong.

Comments
Add a comment...
required
required, hidden, gravatared

required, markdown enabled (help)
you type:you see:
*italics*italics
**bold**bold
[stolen from reddit!](http://reddit.com)stolen from reddit!
* item 1
* item 2
* item 3
  • item 1
  • item 2
  • item 3
> quoted text
quoted text
Lines starting with four spaces
are treated like code:

    if 1 * 2 < 3:
        print "hello, world!"
Lines starting with four spaces
are treated like code:
if 1 * 2 < 3:
    print "hello, world!"