If Foreign Key Not Exist Then Add Foreign Key Constraint(Or Drop a Foreign Key Constraint If Exist) without using Name?

前端 未结 4 1780
故里飘歌
故里飘歌 2021-02-19 12:48

I am finding difficulties to creating a a query. Let say I have a Products and Brands table. I can add a foreign key using this command,

          ALTER TABLE Pr         


        
相关标签:
4条回答
  • 2021-02-19 13:22

    First of all, you should always name your FKs and all other constraints in order to save yourself trouble like this.

    But, if you don't know the name of FK you can check it using multiple system views:

    IF NOT EXISTS 
    (
        SELECT * FROM sys.foreign_key_columns fk 
        INNER JOIN sys.columns pc ON pc.object_id = fk.parent_object_id AND pc.column_id = fk.parent_column_id 
        INNER JOIN sys.columns rc ON rc.object_id = fk.referenced_object_id AND rc.column_id = fk.referenced_column_id
        WHERE fk.parent_object_id = object_id('Products') AND pc.name = 'BrandID'
        AND fk.referenced_object_id = object_id('Brands') AND rc.NAME = 'ID'
    )
    ALTER TABLE Products 
    ADD CONSTRAINT Your_New_FK_NAME FOREIGN KEY (BrandID)
    REFERENCES Brands(ID)
    
    0 讨论(0)
  • 2021-02-19 13:23

    You can use this as well.

    IF(OBJECT_ID('FK_Products_Brands', 'F') IS NULL)
    ALTER TABLE [dbo].[Products] WITH CHECK ADD CONSTRAINT [FK_Products_Brands] FOREIGN KEY([BrandID]) REFERENCES [dbo].[Brands] ([Id])
    
    0 讨论(0)
  • 2021-02-19 13:25

    To do this without knowing the constraint's name and without inner joins, you can do:

    IF NOT EXISTS(SELECT NULL FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE [TABLE_NAME] = 'Products' AND [COLUMN_NAME] = 'BrandID')
    BEGIN
        ALTER TABLE Products
        ADD FOREIGN KEY (BrandID)
        REFERENCES Brands(ID)
    END
    

    If you wanted to, you could get the name of the contraint from this table, then do a drop/add.

    0 讨论(0)
  • 2021-02-19 13:39

    Try this:

    IF NOT EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = object_id(N'[dbo].[FK_Products_Brands]') AND OBJECTPROPERTY(o.object_id, N'IsForeignKey') = 1)
    BEGIN
        ALTER TABLE [dbo].[Products] WITH CHECK ADD CONSTRAINT [FK_Products_Brands] FOREIGN KEY([BrandID]) REFERENCES [dbo].[Brands] ([Id])
    END
    
    0 讨论(0)
提交回复
热议问题