tags:

views:

24

answers:

1

Hi,

Bit rusty on the sql side as I have not touched in a while

I have added a foreign key constraint using the Diagram and clearly says that there is a fk relationship.

However when scripting the table or viewing the keys in SQL Server explorer I cannot see the grey key.

Am I missing something? Not sure I am doing it correctly.

How do you create one programatically between 2 tables? Should it appear in the Explorer under keys?

Thanks a lot for any input

+2  A: 

To create the FK relationship, use this syntax:

ALTER TABLE dbo.ChildTable
  ADD CONSTRAINT FK_ChildTable_ParentTable
  FOREIGN KEY (FK column in child table)
  REFERENCES dbo.ParentTable(column in parent table)

and possibly define what happens on UPDATE or DELETE of the primary key in the parent table:

  ON DELETE ...... (CASCADE, NO ACTION, SET NULL)
  ON UPDATE ...... (CASCADE, NO ACTION, SET NULL)

You should be able to query the data dictionary views to check if that FK constraint is really in there:

SELECT
    fk.NAME,
    OBJECT_NAME(parent_object_id) 'Child table',
    OBJECT_NAME(referenced_object_id) 'Parent table',
    fk.*
FROM sys.foreign_keys fk

This will list all existing foreign keys in your current database.

marc_s
Hi,Just seen your post.Thanks a lot for your time.Querying the relationships they are there however still not showing in Explorermmmm Missing something??
@devnet247: not sure - do you have any filtering going by any chance?? Are you sure you're looking at the same server/database?? Or are you querying on your local machine, but Explorer shows you your dev server? (has happened to me before.....)
marc_s
They all apperead now and dont know why.thanks alot