Search code examples
sqlsql-serverinsertidentity-columnbidirectional-relation

What would my SQL statement be to insert "Arnold Schwarzenegger" and "Hasta la vista baby" into these two empty SQL tables?


What would my statement be to insert "Arnold Schwarzenegger" and "Hasta la vista baby" into the following empty SQL tables?

The title of this question was originally going to be "How to insert the first records into SQL tables with bidirectional associations and autogenerated integer PK?" but I wasn't sure if I was phrasing that correctly... Basically, I have two tables Actors and CatchPhrases.

Actors looks like:

  ActorId                  int             NOT NULL  PK (autogenerated by db)
  FavoriteCatchPhraseId    int             NOT NULL  FK
  Name                     varchar(200)    NOT NULL

CatchPhrases looks like:

  CatchPhraseId            int             NOT NULL  PK (autogenerated by db)
  ActorId                  int             NOT NULL  FK
  PhraseText               varchar(500)    NOT NULL

So, Actors can have multiple catch phrases but must have at least one. A catch phrase is associated with an actor. There is currently no data in either table.


Solution

  • I would model it differently to avoid a bidirectional relation (which would be difficult to do). Simply add a column (IsFavorite) to the CatchPhrases table. Either use a constraint or business rule in code to limit the number of catch phrases marked as a favorite for each actor to one.

    Actors:

    ActorId                  int             NOT NULL  PK (autogenerated by db)
    Name                     varchar(200)    NOT NULL
    

    CatchPhrases:

    CatchPhraseId            int             NOT NULL  PK (autogenerated by db)
    ActorId                  int             NOT NULL  FK
    PhraseText               varchar(500)    NOT NULL
    IsFavorite               bit             NOT NULL
    

    Make sure that you have an index on ActorId for the CatchPhrases table so you can quickly find the actor's catch phrases.

    Alternatively, using a join table -- which would allow multiple actors to have the same catch phrase.

    Actors:

    ActorId                  int             NOT NULL PK (autogenerated by db)
    Name                     varchar(200)    NOT NULL
    

    ActorCatchPhrases

    ActorId                  int             NOT NULL PK (FK to Actors)
    CatchPhraseId            int             NOT NULL PK (FK to CatchPhrases)
    IsFavorite               bit             NOT NULL
    

    CatchPhrases

    PhraseId                 int             NOT NULL PK (autogenerated by db)  
    PhraseText               varchar(500)    NOT NULL