Below is pseudo-code for SQL Server stored procedure I need to write:
int[] followers = (select FollowerID from StoreFollower where StoreId = @storeId)
insert into Message (senderId, recipientId)
values (@senderId, followers[0])
int rootMessageId = last_id()
foreach (int follower in followers.Skip(1))
insert into Message (senderId, recipientId, rootMessageId)
values (@senderId, follower, rootMessageId
It gets all Store‘s follower IDs, creates a record in Message for the first one. Then it creates a Message for each subsequent follower ID, also specifying ID of the first Message record in the batch.
I need to convert this to SQL Server stored procedure, however I never wrote one before so I’m hesitant. Should I use a table variable to hold select result? Should I use arrays? What is the closest match to foreach here? How do I slice off the first element?
I would very much appreciate a sketch of such proc, just to know what to look further at.
My stab at it in T-SQL. I assume that (a)
FollowerIDisint, (b)@storeIdand@senderIDar parameters of the stored procedure.HTH