Script to drop and re-create all foreign keys

By at November 22, 2008 01:36
Filed Under:

------------
-- Generate Drop Disable.sql

SET NOCOUNT ON

print 'USE ' + DB_NAME() 
print ''

-- Generate Drops for All Foreign Keys in Database
print '-- Drop Foreign Keys'
print ''


select distinct 'ALTER TABLE ['+ SCHEMA_NAME(CAST(OBJECTPROPERTYEX(tbl.id , 'SchemaId') AS INT)) +'].[' + object_name(fkeyid) + 

'] DROP CONSTRAINT ' + object_name(constid) + 

CHAR(13) + CHAR(10) + 'go' 

from sysforeignkeys 

JOIN sysobjects ON sysobjects.id = constid 
JOIN sysobjects tbl ON tbl.id = fkeyid 

JOIN syscolumns col ON col.id = fkeyid AND col.colid = fkey 
JOIN sysobjects ltbl ON ltbl.id = rkeyid 

JOIN syscolumns lcol ON lcol.id = rkeyid AND lcol.colid = rkey 


go 


-- Generate Disable all triggers
print ''
print '-- Disable Triggers'
print ''

select distinct 'ALTER TABLE [dbo].[' + OBJECT_NAME(parent_obj) +
    '] DISABLE TRIGGER ALL ' + 
    CHAR(13) + CHAR(10) + 'go'
FROM sysobjects
WHERE OBJECTPROPERTY(id, 'IsTrigger') = 1 and parent_obj in
    (select id from sysobjects where xtype = 'U')
go

-----------------------------------------------------------
-- Generate Add Enable.sql

SET NOCOUNT ON

print 'USE ' + DB_NAME() 
print ''

-- Generate Adds for All Foreign Keys in Database
print '-- Add Foreign Keys'
print ''

DECLARE @fkName varchar(800),@schema VARCHAR(800), @tabName varchar(800), @refName varchar(800)
DECLARE @isDel int, @isUpd int, @fkCol varchar(8000), @refCol varchar(8000)
DECLARE @pline varchar(8000)

DECLARE fkCursor CURSOR FOR

    SELECT
     SCHEMA_NAME(CAST(OBJECTPROPERTYEX(tbl.id , 'SchemaId') AS INT)),
     sysobjects.name,
     tbl.name,
     ltbl.name,
    OBJECTPROPERTY ( constid , 'CnstIsDeleteCascade' ),
    OBJECTPROPERTY ( constid , 'CnstIsUpdateCascade' )
    FROM
     sysforeignkeys
     JOIN sysobjects ON sysobjects.id = constid
     JOIN sysobjects tbl ON tbl.id = fkeyid
     JOIN syscolumns col ON col.id = fkeyid AND col.colid = fkey
     JOIN sysobjects ltbl ON ltbl.id = rkeyid
     JOIN syscolumns lcol ON lcol.id = rkeyid AND lcol.colid = rkey    
    ORDER BY sysobjects.name    

OPEN fkCursor

FETCH NEXT FROM fkCursor 
    INTO @schema, @fkName, @tabName, @refName, @isDel, @isUpd

WHILE @@FETCH_STATUS = 0
BEGIN
    select @fkCol = NULL
    SELECT @fkCol = ISNULL(@fkCol + ', ','') + '[' + col_name(fkeyid, fkey) + ']'
    from sysforeignkeys 
    where object_name(constid) = @fkName 
    order by keyno

    select @refCol = NULL
    SELECT @refCol = ISNULL(@refCol + ', ','') + '[' + col_name(rkeyid, rkey) + ']'
    from sysforeignkeys 
    where object_name(constid) = @fkName 
    order by keyno

    select @pline = 'ALTER TABLE [' + @schema + '].[' + @tabName + '] ADD CONSTRAINT [' + @fkName + ']' +
    CHAR(13) + CHAR(10) + '   FOREIGN KEY (' + @fkCol + ') REFERENCES [' + @schema + '].[' + @refName +
    '] (' + @refCol + ')'
    
    if @isDel = 1 
        select @pline = @pline + CHAR(13) + CHAR(10) + 
            '     ON DELETE CASCADE'
    if @isUpd = 1 
        select @pline = @pline + CHAR(13) + CHAR(10) + 
            '     ON UPDATE CASCADE'
    select @pline = @pline + CHAR(13) + CHAR(10) + 'go'
    print @pline
    FETCH NEXT FROM fkCursor 
        INTO @schema, @fkName, @tabName, @refName, @isDel, @isUpd
END

CLOSE fkCursor
DEALLOCATE fkCursor
GO

-- Generate Enable all triggers
print ''
print '-- Enable Triggers'
print ''

select distinct 'ALTER TABLE [dbo].[' + OBJECT_NAME(parent_obj) +
    '] ENABLE TRIGGER ALL ' + 
    CHAR(13) + CHAR(10) + 'go'
FROM sysobjects
WHERE OBJECTPROPERTY(id, 'IsTrigger') = 1 and parent_obj in
    (select id from sysobjects where xtype = 'U')
go

Comments

1/14/2010 10:07:02 AM #

cars

that is good information for me, thanks

cars United States | Reply

1/17/2010 3:03:57 AM #

0xc0000005

Nice script,it really helped me with one issue

0xc0000005 United States | Reply

1/17/2010 4:48:14 PM #

Wine Aerator

i thought you may want to know.it doesn't show up properly in my blackberry, (i am using pearl) but im on my laptop now and no problem browsing.

Wine Aerator United States | Reply

2/28/2010 7:06:33 PM #

Fatcow

Should I get a Virtual Private Server? Currently I am using fatcow but they keep shutting me down because of high server overload. Im getting about 4,000 UV a day. What hosting should I get?

Fatcow United States | Reply

3/2/2010 4:13:19 PM #

wow mobiles

WoW Mobile is awesome! I get free mobile service with t-mobile because I refered 3 people to wow. You can too!

wow mobiles United States | Reply

3/6/2010 5:25:04 AM #

Migrain

Thanks for this piece of code. I have terrible migrain right now so I can't generate good ideas on my own...

Migrain United States | Reply

3/14/2010 6:56:18 AM #

general electric cooktop

Hvala vam za dobar post puno hvala

general electric cooktop United States | Reply

3/20/2010 11:37:23 PM #

cheap prom Dresses

I have terrible migrain right now so I can't generate good ideas on my own...

cheap prom Dresses People's Republic of China | Reply

3/21/2010 2:42:21 PM #

Smart Shop

Great Tips! Thanks for sharing such a useful tips.

Smart Shop Italy | Reply

3/28/2010 4:30:54 AM #

discount golf bags

I hope you remembered to put your clock forward one hour.

discount golf bags United Kingdom | Reply

4/4/2010 5:05:57 PM #

carpfishing

Carp coarse fishing has to be understood by knowing what it is not.

carpfishing United States | Reply

4/6/2010 7:55:46 PM #

Memorials

Hello nice blog im from newcastel i found this on yahoouk I seen it on the top ten searches i found this blog very interesting good luck with it i will return to this blog soon

Memorials United States | Reply

4/19/2010 11:59:06 AM #

carkit bluetooth

Great blog here. Keep it up! Please try to include more information if possible.

carkit bluetooth United States | Reply

4/25/2010 1:36:42 AM #

Dave

I love your post

Dave Trinidad and Tobago | Reply

4/27/2010 1:45:51 PM #

How to get ripped

Couldnt be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks again for sharing this free online

How to get ripped United States | Reply

5/12/2010 7:04:09 PM #

Door Handles & Knobs

Hi there, I just wanted to say thanks for this informative post, can you please allow me to post it on my blog?

Door Handles & Knobs United States | Reply

5/17/2010 3:49:29 PM #

LAURA DAWSON

hello good blog yea nice work our blog will soon be adding reviews on blogs and add them to our blogs as the top best 10 blogs to visit we also do reviews on product recalls  all types of reviews thank you

LAURA DAWSON United States | Reply

6/4/2010 5:04:08 PM #

real touch

I romance your blog, Its great to discover not every body is just posting a mess of rubbish these days!

real touch United States | Reply

6/6/2010 4:13:14 PM #

retail store displays

Brilliant stuff, man!  What you have to say is really important and Im glad you took the time to share it.  What you said really spoke to me and I hope that I can learn more about this.  Thanks for sharing your opinion.  I am yet to find anything as enlightening as this on the web.

retail store displays United States | Reply

6/8/2010 5:53:31 AM #

California car insurance companies

This just might be slightly of a different subject but everyone needs auto insurance and if you know how to find it you can very easily save a whole lot of cash. Let me know if you need a few tips.

California car insurance companies United States | Reply

6/9/2010 8:17:46 AM #

real touch

I fancy your blog, Its very good to observe not every person is just posting a bunch of nonsense these days!

real touch United States | Reply

6/9/2010 3:14:56 PM #

http://www.cheapnewlaptopsforsale.com

Good post, liked the idea, keep up the good work!

http://www.cheapnewlaptopsforsale.com United States | Reply

6/16/2010 4:34:08 PM #

Chad Wolslegel

You certain do know what youre discussing.  Man, this website is just excellent!  I cant wait to read much more of what youve obtained to express.  Im truly happy that I came across this when I did due to the fact I was truly starting to get bored while using whole blogging scene.  Youve turned me around, man!

Chad Wolslegel United States | Reply

6/17/2010 8:58:50 PM #

glass etching cream

Wonderful blog! I saw it at Yahoo and I must say that entries are well thought of. I will be coming back to see more posts soon.

glass etching cream United States | Reply

6/18/2010 5:46:29 AM #

starcraft 2 beta

Any of you guys play PC Games?  If so I don't suppose any of you have been looking into Blizzard's new RTS?

starcraft 2 beta United States | Reply

6/25/2010 7:42:38 AM #

Robert Dampson

Always enjoy reading spot on articles by an author who is obviously knowledgeable on their chosen subject….Now is the perfect time (summer now)to spend some money to grab those fancy dress and accessories! LOL….. Keep up the great work, see you next time

Robert Dampson New Zealand | Reply

6/27/2010 5:38:44 AM #

laptop cheap review

great post. It's really helpful and I will bookmark this page. thanks

laptop cheap review Armenia | Reply

6/28/2010 3:37:40 PM #

Tinnitus Remedies

This is actually the 2nd time I have come across your web site within the last few weeks.  Seems as if I should take note of it.

Tinnitus Remedies United States | Reply

7/2/2010 1:10:33 AM #

grace

Hello,
Very good blog post. I found your info very helpful and useful. I have been need some help with some of the things you had on here so I just wated to say thank you for the great help!!

grace United States | Reply

7/13/2010 8:10:20 PM #

cheap jerseys

Good post, liked the idea, keep up the good work!

cheap jerseys People's Republic of China | Reply

7/15/2010 8:06:48 AM #

United Kingdom | Reply

7/20/2010 4:46:17 AM #

The Driving Schools

Awesome keep this up champion.

The Driving Schools United States | Reply

7/31/2010 11:06:38 AM #

extreme mountain biking

You make a great point.  Got some great information here.  I think that if more people thought about it that way, theyd have a better time understanding the issue.  Your view is definitely something Id like to see more of.  Thanks for this blog.  Its fantastic and so is what youve got to say.

extreme mountain biking United States | Reply

8/2/2010 4:22:36 AM #

Fishing Guideline

Thanks for the blog post!  Really helpful information.

Fishing Guideline Guatemala | Reply

8/6/2010 7:15:41 PM #

my webblog

I really like the information from you. I also have some great information about the automotive manuals.

my webblog United States | Reply

8/10/2010 2:25:36 AM #

jason

i hope the market starts turning around soon

jason Thailand | Reply

8/19/2010 12:39:32 PM #

Lera Fraile

nice post. thanks for your shareing. i amost agree what you write. but i think some place need expain more, then we can read clearly ,then it will help me easy understand it. at the all , thanks again for your shareing

Lera Fraile United States | Reply

8/30/2010 8:17:04 PM #

under floor heating

well,I have terrible migrain right now so I can't generate good ideas on my own...

under floor heating India | Reply

9/2/2010 1:39:57 PM #

starcraft 2 strategy

Very useful,thanks for sharing keep on going another one.You have gained a new reader

starcraft 2 strategy United States | Reply

9/5/2010 8:20:57 PM #

Shure

Hows it Going great and fun to read.  I am a big follower of the topics talked about.  I also enjoy reading the other peoples thoughts, but it seems like that a great deal of followers should keep on topic to try and add something to the original topic.  I would also encourage all of you to bookmark this blog to your favourite service to help get the word out.  Thanks

Shure United States | Reply

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading