简体   繁体   中英

Which is faster? Trigger After Insert or direct Stored Procedure

I am uploading bulks of Excel Records in a temp table. Then I need to sum these rows and put the summed up to the main table with PK.

I made a trigger After Insert that checks if the inserted is already existing in the main table (Not existing will insert, existing will update all columns in that row).

so to trigger this TRIGGER i need to Insert INTO another temp Table

INSERT INTO TEMPTBL (select SUM(...)...* from temptable)

then the trigger would insert / update to the main table.

I was wondering if that is the proper way or just using a single TEMP table then use SP to do the checking with 1 CURSOR FETCH ( for the Updating of the existing rows) then the Insert for the rest.

Thanks in advance for reading. Just need to know which would be ideal / faster because these would be handling multi users ( please dont mind the deadlocking yet :D )

Both of the approaches that you're suggesting sound procedural (row-by-row), but I think there should be a set based solution (all records at once) for what you're doing.

Instead of the trigger or cursor, insert all of your records at once, and in your insert statement, include a check to exclude any records that already exist in the table. Something like:

INSERT INTO YourTable (Column1, Column2...)
SELECT Column1, Column2...
FROM TempTable tt
WHERE NOT EXISTS (
    SELECT 1
    FROM YourTable yt
    WHERE tt.ID = yt.ID
)

EDIT:

For your update, you can do something similar. Before your insert, join your temp table to your existing table, and update the matching records:

UPDATE yt
SET Column1 = tt.Column1, Column2 = tt.Column2
FROM
    YourTable yt JOIN
    TempTable tt ON tt.ID = yt.ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM