Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT then UPDATE those records and then return them in STORED PROCEDURE

Tags:

sql

sql-server

I want to do a SELECT to get a list of ID's, do an update based on those ID's and then return those records.

Something like this I guess, I just do not know the syntax:

  SELECT WebHookLogIDs = FROM WebHookLog 
                WHERE Processing=0
                    AND Processed=0
                        AND Paused=0
                            ORDER BY FailCount ASC, WebHookLogID DESC

    UPDATE WebHookLog
        SET Processing = 1
            WHERE WebHookLogID IN(WebHookLogIDs)

    SELECT * FROM WebHookLog 
            WHERE WebHookLogID IN(WebHookLogIDs)
like image 325
Slee Avatar asked Jan 15 '13 12:01

Slee


2 Answers

I think its better to put data in Temp table, than insert data in it

because at the last you want to return those record back , so you need to use temp table

DECLARE @Table1 TABLE (WebHookLogIDs INT)

Insert into @Table1(WebHookLogIDs )
SELECT WebHookLogIDs  FROM WebHookLog 
                WHERE Processing=0
                    AND Processed=0
                        AND Paused=0
                            ORDER BY FailCount ASC, WebHookLogID DESC

    UPDATE WebHookLog
        SET Processing = 1
            WHERE WebHookLogID IN( select WebHookLogIDs from @Table1)

    SELECT * FROM WebHookLog 
            WHERE WebHookLogID IN(select WebHookLogIDs from @Table1)
    DROP TABLE @Table1
like image 69
Pranay Rana Avatar answered Sep 30 '22 17:09

Pranay Rana


You can't do UPDATE with SELECT with the same SQL Statement. You can however, UPDATE with JOIN instead of selecting the ID's like this:

UPDATE w1
SET w1.Processing = 1
FROM WebHookLog w1
INNER JOIN WebHookLog w2  ON w1.WebHookLogID = w2.WebHookLogID 
                         AND w2.Processing    = 0
                         AND w2.Processed     = 0
                         AND w2.Paused        = 0;

Later, you can do another SELECT clause.

like image 37
Mahmoud Gamal Avatar answered Sep 30 '22 18:09

Mahmoud Gamal