Unique constraint and Foreign key

  • Just wondering.....

    One of our developers just steped into our office and asked why it is not possible to create a Foreign key to a Unique constraint ??

    Explanation on this;

    Table A has column 1 holding a Primay key and two columns (2 and 3) holding a Unique combination (and some more columns).

    He created an Unique constraint on column 2 and 3 together.

    He wanted to use this Unique combination to point to table B (instead of the table 1's PK)

    so he tried to create a foreign key on a column in table B but an error popped up prompting;

    The columns in table 'TABLE_A' do not match an existing primary key or UNIQUE constraint.

    Ok - these two columns ar no PK but the hold an Unique constraint......

    Can anyone explain why this error popped up or how to solve this?

    Regrads,

    GKramer

  • gkramer 23701 (7/3/2015)


    Just wondering.....

    One of our developers just steped into our office and asked why it is not possible to create a Foreign key to a Unique constraint ??

    Explanation on this;

    Table A has column 1 holding a Primay key and two columns (2 and 3) holding a Unique combination (and some more columns).

    He created an Unique constraint on column 2 and 3 together.

    He wanted to use this Unique combination to point to table B (instead of the table 1's PK)

    so he tried to create a foreign key on a column in table B but an error popped up prompting;

    The columns in table 'TABLE_A' do not match an existing primary key or UNIQUE constraint.

    Ok - these two columns ar no PK but the hold an Unique constraint......

    Can anyone explain why this error popped up or how to solve this?

    Regrads,

    GKramer

    The unique constraint needs to be on the single column in table A which is being referenced.

    If you haven't even tried to resolve your issue, please don't expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.

  • gkramer 23701 (7/3/2015)


    One of our developers just steped into our office and asked why it is not possible to create a Foreign key to a Unique constraint ??

    It is possible. Unique indexes work fine as well. Where your developer probably made the mistake is in not having the foreign key on both columns of the unique constraint. If he tried to reference just on one, then he will get an error because the unique constraint is on two columns, not 1.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply