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

前端 未结 4 1774
故里飘歌
故里飘歌 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: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.

提交回复
热议问题