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

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

提交回复
热议问题