开发者

Execute stored procedure for each record in table

开发者 https://www.devze.com 2023-01-04 12:14 出处:网络
I have two tables that need to be updated, Master and Identifiers: Master --MasterID (PK) --ModifiedDate

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

Master

--MasterID (PK)

--ModifiedDate

--ModifiedBy

Identifiers

--Identifie开发者_高级运维rID

--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!


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号