Iterate through rows in SQL Server 2008

后端 未结 3 2223
渐次进展
渐次进展 2020-12-14 09:07

Consider the table SAMPLE:

id       integer
name     nvarchar(10)

There is a stored proc called myproc. It takes only one para

3条回答
  •  生来不讨喜
    2020-12-14 09:23

    If you must iterate(*), use the construct designed to do it - the cursor. Much maligned, but if it most clearly expresses your intentions, I say use it:

    DECLARE @ID int
    DECLARE IDs CURSOR LOCAL FOR select ID from SAMPLE where Name = @NameParameter
    
    OPEN IDs
    FETCH NEXT FROM IDs into @ID
    WHILE @@FETCH_STATUS = 0
    BEGIN
        exec myproc @ID
    
        FETCH NEXT FROM IDs into @ID
    END
    
    CLOSE IDs
    DEALLOCATE IDs
    

    (*) This answer has received a few upvotes recently, but I feel I ought to incorporate my original comment here also, and add some general advice:

    In SQL, you should generally seek a set-based solution. The entire language is oriented around set-based solutions, and (in turn) the optimizer is oriented around making set-based solutions work well. In further turn, the tools that we have available for tuning the optimizer is also set-oriented - e.g. applying indexes to tables.

    There are a few situations where iteration is the best approach. These are few are far between, and may be likened to Jackson's rules on optimization - don't do it - and (for experts only) don't do it yet.

    You're far better served to first try to formulate what you want in terms of the set of all rows to be affected - what is the overall change to be achieved? - and then try to formulate a query that encapsulates that goal. Only if the query produced by doing so is not performing adequately (or there's some other component that is unable to do anything other than deal with each row individually) should you consider iteration.

提交回复
热议问题