如何在循环中运行存储过程

时间:2011-01-30 12:50:34

标签: sql sql-server tsql

我有"Departments" (ID,deptID)

的表格
ID  parentdeptID  
2 null  
3 null  
7 2  
8 2  
9 3  

和第二个表"Filter"仅包含ID

ID  
2  
9  

和只有输入参数@deptID的存储过程,输出是根据输入ID连接某些表的结果

我的问题是:从“过滤”表中读取并获取ID,并为每个ID获取其子项(如果有) 在我们的例子中:

2,7,8,9 (2,9 from "Filter" and 7,8 from "Departments" as childs of 2)

然后对于这4个ID中的每一个,通过ID

执行存储过程

这是概述,如果任何人有更好的方法而不使用存储过程,欢迎他

2 个答案:

答案 0 :(得分:2)

我不确定我是否理解你的模型,但是这里是你如何做循环并在其中执行存储过程:

编辑我想我现在对你的问题了解得更好。

declare @filterId int
declare @deptId int

select @filterId = min(ID) from Filter
while @filterId is not null
   begin
      -- run the stored procedure for the main filter ID
      exec procedureName @filterId

      -- run the SP for the related IDs in Department table
      select @deptId = min(ID) from Departments where parentdeptID = @filterID
      while @deptId is not null
         begin
            exec procedureName @deptId
            select @deptId = min(ID) from Departments where ID > @deptId and parentdeptID = @filterID
         end

      select @filterId = ID from Filter where ID > @filterId
   end

希望这能让你开始。

答案 1 :(得分:1)

要在没有存储过程的情况下执行您想要的操作,您应该将DeptID与存储过程中的查询一起加入。

假设您的SP执行select DeptID, DeptInfo from @SomeOtherTableWithData where DeptiID = @DeptID

以下是使用表替换存储过程的示例代码。

-- Setup sample data
declare @Departments table (DeptID int, ParentDeptID int)
declare @Filter table (DeptID int)
declare @SomeOtherTableWithData table (DeptID int, DeptInfo varchar(50))

insert into @Departments values (2, null)  
insert into @Departments values (3, null)  
insert into @Departments values (7, 2)  
insert into @Departments values (8, 2)  
insert into @Departments values (9, 3) 

insert into @Filter values(2)
insert into @Filter values(9)

insert into @SomeOtherTableWithData values (2, 'Info DeptID 2')
insert into @SomeOtherTableWithData values (3, 'Info DeptID 3')
insert into @SomeOtherTableWithData values (7, 'Info DeptID 7')
insert into @SomeOtherTableWithData values (8, 'Info DeptID 8')
insert into @SomeOtherTableWithData values (9, 'Info DeptID 9')

-- Get the DeptID's into temporary table #DeptIDs
select D.DeptID  -- Parents
into #DeptIDs 
from @Departments as D
    inner join @Filter as F
        on D.DeptID = F.DeptID
union
select D.DeptID  -- Children
from @Departments as D
    inner join @Filter as F
        on D.ParentDeptID = F.DeptID

-- Use #DeptID in a join with the query in the stored procedure
select S.DeptID, S.DeptInfo
from #DeptIds as D
    inner join @SomeOtherTableWithData as S
        on D.DeptID = S.DeptID

-- Drop the temporary table
drop table #DeptIDs

结果是

DeptID  DeptInfo
2   Info DeptID 2
7   Info DeptID 7
8   Info DeptID 8
9   Info DeptID 9

如果只需要一个SQL语句,则可以使用子查询而不是临时表。