Search code examples
sql-server-2008stored-proceduresenumerationpseudocode

How to translate this C#-like code to an SQL Server stored proc


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.


Solution

  • My stab at it in T-SQL. I assume that (a) FollowerID is int, (b) @storeId and @senderID ar parameters of the stored procedure.

    DECLARE @FirstFollower int
    DECLARE @FirstMessage int
    
    --Get the first follower (i.e. smallest FollowerID, hopefully that's what you mean
    --otherwise you need an appropriate ORDER BY clause here
    SELECT @FirstFollower=TOP(1) FollowerId from StoreFollower 
    where StoreId = @storeId
    
    --Store message for first follower and get root message id
    INSERT INTO Message (senderId, recipientId)
    VALUES(@senderId, @FirstFollower)
    
    SELECT @FirstMessage=SCOPE_IDENTITY()
    
    --store a message per follower except the first. Same conditions apply here
    --regarding the order of the followers as in the first SELECT query
    INSERT INTO Message(senderId, recipientId, rootMessageId)
    SELECT @senderId, FollowerID, @FirstMessage
    FROM StoreFollower WHERE
    FollowerID <> @FirstFollower
    

    HTH