T-SQL: Looping through an array of known values

后端 未结 7 1650
深忆病人
深忆病人 2021-01-30 00:51

Here\'s my scenario:

Let\'s say I have a stored procedure in which I need to call another stored procedure on a set of specific ids; is there a way to do this?

i

7条回答
  •  情深已故
    2021-01-30 01:02

    use a static cursor variable and a split function:

    declare @comma_delimited_list varchar(4000)
    set @comma_delimited_list = '4,7,12,22,19'
    
    declare @cursor cursor
    set @cursor = cursor static for 
      select convert(int, Value) as Id from dbo.Split(@comma_delimited_list) a
    
    declare @id int
    open @cursor
    while 1=1 begin
      fetch next from @cursor into @id
      if @@fetch_status <> 0 break
      ....do something....
    end
    -- not strictly necessary w/ cursor variables since they will go out of scope like a normal var
    close @cursor
    deallocate @cursor
    

    Cursors have a bad rep since the default options when declared against user tables can generate a lot of overhead.

    But in this case the overhead is quite minimal, less than any other methods here. STATIC tells SQL Server to materialize the results in tempdb and then iterate over that. For small lists like this, it's the optimal solution.

提交回复
热议问题