SQL 2008 :: Relational Database :: How to add a Foreign Key Constraints Using Query And Graphically

Using t-SQL:

We already have 2 tables:

Product:
ProductID - int-primary key-indexed
Name - nvarchar(15)
testProductAttribute
testProductAttributeID- int-primary key-indexed
ProductID-int

Now we would like to create a foreign key relationship between these 2 tables. Key benefit is that, if there is a attribute data for a product in testProductAttribute table, we will not be able delete the record from Product table. (Off-course we can change this option)

ALTER TABLE testProductAttribute
ADD FOREIGN KEY (ProductID)
REFERENCES Product(ProductID)

Using Graphically:

First of all, we want to delete the previously created Foreign Key:

ALTER TABLE testProductAttribute
DROP CONSTRAINT  FK__testProdu__Produ__38996AB5

FK__testProdu__Produ__38996AB5 is the system generated name for our previous query which can be different and we can find the name from “Keys” folder of the testProductAttribute table.

Now please go through as follows:

 

This slideshow requires JavaScript.

Advertisements
By simplemsexchange Posted in SQL 2008

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s