views:

53

answers:

1

I have two tables that need to be updated, Master and Identifiers:

Master
--MasterID (PK)
--ModifiedDate
--ModifiedBy

Identifiers
--IdentifierID
--MasterID (FK to Master)
--Identifier
--IdentifierType
--ModifiedDate
--ModifiedBy

The Master table's sole reason for existence is to tie different Identifiers to a single person.

I receive a file that contains new Identifier info (MasterID (if available), Identifier, IdentifierType) which needs to be inserted into Identifiers. The records that have a MasterID are obviously simple to insert; the records without one, however, are a bit more difficult.

A new MasterID must be generated, prior to inserting the data into the Identifiers table, so it can be used as the FK.

I was thinking that a stored proc something along the lines of this might work:

DECLARE @IDOutput INT

INSERT INTO Master
(
    ModifiedDate,
    ModifiedBy
)
VALUES
(
    GETDATE(),
    'Robert'
)

SET @IDOutput = SCOPE_IDENTITY()

INSERT INTO Identifiers
(
    MasterID,
    Identifier,
    IdentifierType,
    ModifiedDate,
    ModifiedBy    
)
VALUES
(
    @IDOutput,
    Identifier, --this comes from input file
    IdentifierType, --this comes from input file
    GETDATE(),
    'Robert'
)

My problem is how to have this stored proc run for each record in my input file. I've read that using a cursor, a stored procedure within a stored procedure, or a temp table might be the way to handle this, but I'm not sure the best way to implement this using one of those methods. Actually, I'm not sure if I'm going about this the right way at all.

Any help regarding this will be greatly appreciated!

+1  A: 

Assuming you have staging table, you can capture many keys using the OUTPUT clause

So instead of looping, you pick out the "master" rows from staging table and insert, storing new keys in a table variable. You then use this to populate the child table.

Something like this:

INSERT INTO Master (ModifiedDate, ModifiedBy, foo)
OUTPUT Inserted.MasterID, Inserted.ModifiedBy INTO @NewKeys
SELECT DISTINCT GETDATE(), 'Robert' FROM StagingTable


INSERT INTO Identifiers
(
    MasterID,
    Identifier,
    IdentifierType,
    ModifiedDate, ModifiedBy    
)
SELECT
    N.MasterID,
    S.Identifier, --this comes from input file
    S.IdentifierType, --this comes from input file
    GETDATE(), N.ModifiedBy
FROM
    StagingTable S
    JOIN
    @NewKeys N ON S.ModifiedBy = N.ModifiedBy

I have to say though: is there mnore to your schema. The master table almost serves no purpose here...

gbn
You're seeing the Master and Identifiers tables in all their glory and, unfortunately, I have no control over their design. A little background: since people can have different "identifiers" (SSN, Driver's License, etc.), the Identifiers table was created. The Master table is what links them all together. There are other tables, of course: Demographics, Addresses, etc., but I am not concerned with those ones.
Robert