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
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)