1

我想实现递归 CTE 而不是跟随游标,因为通过在游标内以编程方式执行存储过程来插入数据需要花费大量时间,尤其是当表中有大量记录时。我已经尝试过 CTE 表达式来解决这个问题,但是我无法用 CTE 生成相同的表达式,而且光标真的很糟糕,我完全想用 CTE 替换它,所以有什么办法可以缩短这个。提前谢谢。

    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  
4

1 回答 1

2

这样的事情吗?

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
于 2013-05-16T09:48:09.417 回答