sql server - How to execute part of the code only once while running multiple instances in T-SQL -
i have stored procedure called business code. code uses parallelism, multiple instances of sp running @ same time depending on conditions.
there logic in sp want execute once. have table (let's call history) holds uid run , datetime when portion of code executed. here's flow:
sp begin -- logic if conditions met, check if history not have entry uid 1. add entry in history current uid 2. run once code sp end
the issue that, @ times, logic above still gets executed multiple times if different instances reach part @ same time. can ensure runs once?
thank you!
begin transaction; insert [history](uid, ...) select @uid, ... not exists ( select * [history] (holdlock) uid = @uid ); if @@rowcount = 1 begin; -- inserted, logic should run once end; commit;
holdlock
(equivalent running transaction under serializable
, more granular) ensures no other transaction running in parallel can insert entry in history
uid; transaction tries block until first insert
finished , return (since row exists). ensure index on uid
exists, otherwise lock lot more healthy performance.
getting code right tricky, make sure test in practice stress-testing concurrent inserts same (and different) uid.