Execute stored procedure programmatically inside recursive CTE instead of Cursor

删除回忆录丶 提交于 2019-12-13 18:20:01

问题


I want to implement recursive CTE instead of following cursor because it takes lot of time to insert data by executing stored procedures programatecally inside cursor especially when there is larger number of records in table. I have tried CTE expression to solve this issue but i was failed to generate same with CTE and cursor really sucks and i totally want to replace it with CTE so is there any way to short out this. Advance thanks.

    Declare @Emp_Id As Numeric    
    Declare CurEmpWeekOff cursor for        
    Select Emp_Id From tblEmployee Where Cmp_Id = @Cmp_Id And Branch_Id = @Branch_Id And Emp_WeekOff_Type = 1    

    open CurEmpWeekOff        
    Fetch next From CurEmpWeekOff Into @Emp_Id    
    while @@Fetch_Status = 0        
    Begin        
  If @Is_Sunday = 1    
   Exec [prcEmployee_WeekoffInsert] @Cmp_Id, @Branch_Id, @Emp_Id, @From_Date, 0, '', @Login_Id, 0    
  If @Is_Monday = 1    
   Exec [prcEmployee_WeekoffInsert] @Cmp_Id, @Branch_Id, @Emp_Id, @From_Date, 1, '', @Login_Id, 0    
  If @Is_Tuesday = 1    
   Exec [prcEmployee_WeekoffInsert] @Cmp_Id, @Branch_Id, @Emp_Id, @From_Date, 2, '', @Login_Id, 0    
  If @Is_Wednesday = 1    
   Exec [prcEmployee_WeekoffInsert] @Cmp_Id, @Branch_Id, @Emp_Id, @From_Date, 3, '', @Login_Id, 0    
  If @Is_Thursday = 1    
   Exec [prcEmployee_WeekoffInsert] @Cmp_Id, @Branch_Id, @Emp_Id, @From_Date, 4, '', @Login_Id, 0    
  If @Is_Friday = 1    
   Exec [prcEmployee_WeekoffInsert] @Cmp_Id, @Branch_Id, @Emp_Id, @From_Date, 5, '', @Login_Id, 0    
  If @Is_Saturday = 1    
   Exec [prcEmployee_WeekoffInsert] @Cmp_Id, @Branch_Id, @Emp_Id, @From_Date, 6, '', @Login_Id, 0    

  Fetch next From CurEmpWeekOff Into @Emp_Id    
    End        
    Close CurEmpWeekOff        
    Deallocate CurEmpWeekOff            
   End  

回答1:


Something like this do?

Declare @Emp_Id As Numeric
DECLARE @TempID INT
DECLARE @DayOfWeek INT

If @Is_Sunday = 1    
  SET @DayOfWeek = 1
  If @Is_Monday = 1    
   SET @DayOfWeek = 2

... INSERT REST HERE
  If @Is_Saturday = 1    
   SET @DayOfWeek = 6 


DECLARE #TempEmp TABLE
(
   ID INT IDENTITY,
   EmpID INT
)

INSERT INTO #TempEmp
(
   EmpID
)
Select Emp_Id From tblEmployee Where Cmp_Id = @Cmp_Id And Branch_Id = @Branch_Id And Emp_WeekOff_Type = 1


WHILE EXISTS (SELECT 1 FROM #TempEmp)
BEGIN

    SELECT TOP 1 @TempID = ID, @Emp_ID = EmpID FROM #TempEmp

    Exec [prcEmployee_WeekoffInsert] @Cmp_Id, @Branch_Id, @Emp_Id, @From_Date, @DayOFWeek, '',      @Login_Id, 0 

    DELETE FROM #TempEmp WHERE ID = @TempId
END


来源:https://stackoverflow.com/questions/16582688/execute-stored-procedure-programmatically-inside-recursive-cte-instead-of-cursor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!