SQL Server: Create an ID field (PK) based on two fields with a trigger-- HELP!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • newDevMan
    New Member
    • Dec 2011
    • 3

    SQL Server: Create an ID field (PK) based on two fields with a trigger-- HELP!

    Ok, So I'm a bit new at SQL Server, and I've researched this everywhere but cannot find a clear answer and/or sample code for a solution:

    -I have a table [Indicators] that has a bunch of fields including [MOE] field and a [Indicator_Selec tor] field, and the [INDid] field, which is the PK.

    -My goal is to auto-generate the [INDid] field (PK) from concatenating the [MOE] and [Indicator_Selec tor] fields. so... [INDid]=[MOE]+[Indicator_Selec tor].

    ---

    My first option was to make the [INDid] field a calculated field, which worked, and it even let me set it as a PK... BUT, SQL server does NOT allow this field to be a FK on a different table, which is crucial for my database. SO... I am told that a TRIGGER can do the trick, and I have found some samples on the internet, but none of them work correctly and are poorly explained.

    Can anyone help me please? Thanks in advanced!!!
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    There's no need to create a third field to combine two other fields to use as a PK. You can set both fields as the PK and make it into a composite key.

    Comment

    • newDevMan
      New Member
      • Dec 2011
      • 3

      #3
      Thanks rabit, and though it is possible, that is NOT an option. I NEED to have the [INDid] field, it is a foreign key for another table that joins with this one. Still need a trigger... Help!
      Last edited by newDevMan; Dec 7 '11, 02:36 AM. Reason: Spelling

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        You can set the foreign key on the composite.

        Comment

        • newDevMan
          New Member
          • Dec 2011
          • 3

          #5
          I need a trigger that generates the field.

          Comment

          • Rabbit
            Recognized Expert MVP
            • Jan 2007
            • 12517

            #6
            If you create a composite foreign key, you don't need a trigger to populate a third field. It would be simpler and the data would be more normalized.

            Comment

            Working...