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

前端 未结 4 1764
故里飘歌
故里飘歌 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: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])
    

提交回复
热议问题