Drop foreign key constraint

  • Hi, I just need a quick and dirty for dropping a foreign key constraint on a table. I don't want to drop all...only one in just one table. thank you!!!!


    Thank you!!,

    Angelindiego

  • Alter Table schema.table

    Drop Constraint FK_Name

  • thank you! I knew it was an easy one, but everything I was looking it was so complicated and didn't address JUST ONE!!

    Merry Christmas!!


    Thank you!!,

    Angelindiego

  • on a similar issue, if you want to drop a FK on a column, but don't know the actual FK constraint name, i made the proc below...

    you simply call

    EXEC DROP_FK_FROM_SPECIFIC_COLUMN TABLENAME,COLUMNNAME

    and it drops any Foreign keys that that field was referencing...especially handy if you have duplicate FK's:

    [font="Courier New"]

    CREATE PROCEDURE [dbo].[DROP_FK_FROM_SPECIFIC_COLUMN]

    @TableName     VARCHAR(30),

    @ColumnName    VARCHAR(30)

    AS

    BEGIN

        DECLARE @Constraint_to_Delete VARCHAR(100)

        DECLARE Constraint_Cursor CURSOR FOR

            SELECT name AS ConstraintName FROM dbo.sysobjects

                WHERE  OBJECTPROPERTY(id, N'IsForeignKey') = 1

                AND id IN

                    (SELECT constid FROM sysforeignkeys

                    INNER JOIN syscolumns  ON sysforeignkeys.fkeyid = syscolumns.id

                    WHERE fkeyid IN (SELECT id FROM sysobjects

                        WHERE name = @Tablename AND OBJECTPROPERTY(id, N'IsUserTable') = 1)

                    AND syscolumns.name = @ColumnName AND fkey =colid)

        OPEN Constraint_Cursor

            FETCH NEXT FROM Constraint_Cursor INTO @Constraint_to_Delete

        WHILE @@FETCH_STATUS = 0

            BEGIN

                PRINT 'ALTER TABLE ' + @TableName + ' DROP CONSTRAINT '+@Constraint_to_Delete

                EXEC ( 'ALTER TABLE ' + @TableName + ' DROP CONSTRAINT '+@Constraint_to_Delete )

            FETCH NEXT FROM Constraint_Cursor INTO @Constraint_to_delete

            END

        CLOSE Constraint_Cursor

        DEALLOCATE Constraint_Cursor

    END[/font]

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • AWESOME!!!!!! Thank you for sharing this!!

    Merry Christmas!!


    Thank you!!,

    Angelindiego

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply