Iterate through rows in SQL Server 2008

后端 未结 3 2187
渐次进展
渐次进展 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:19

    I just declare the temporary table @sample and insert the all rows which have the name='rahul' and also take the status column to check that the row is iterated.and using while loop i iterate through the all rows of temporary table @sample which have all the ids of name='rahul'

    use dumme
    
    Declare @Name nvarchar(50)
    set @Name='Rahul'
    DECLARE @sample table (
    
        ID int,
        Status varchar(500)
    
        )
    insert into @sample (ID,status) select ID,0 from sample where sample=@name
    while ((select count(Id) from @sample where status=0 )>0) 
    begin
        select top 1  Id  from @sample where status=0 order by Id
        update @sample set status=1  where Id=(select top 1  Id  from @sample where status=0 order by Id) 
    end
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 09:42
    Declare @retStr varchar(100)
    
    select @retStr = COALESCE(@retStr, '') + sample.ID + ', '
    from sample 
    WHERE sample.Name = @nameparameter 
    select  @retStr = ltrim(rtrim(substring(@retStr , 1, len(@retStr )- 1)))
    
    Return  ISNULL(@retStr ,'') 
    
    0 讨论(0)
提交回复
热议问题