将此查询转换为游标

时间:2016-11-07 19:42:23

标签: sql-server cursor

这就是我现在所拥有的,但我仍然收到错误:

  

Ms 16916,Level 16,State 1,Line 239   名为' sumCurSalaryActiveEmps'的光标不存在。
  Msg 16917,Level 16,State 2,Line 258   光标未打开   Msg 16916,Level 16,State 1,Line 266   名为' sumCurSalaryActiveEmps'的光标不存在。
  Msg 16916,Level 16,State 1,Line 267   名为' sumCurSalaryActiveEmps'的光标不存在。

DECLARE @sumCurSal decimal(10,2) 
DECLARE sumCurSalaryActiveEmp CURSOR Local FAST_FORWARD FOR
SELECT 
SUM(Salary.Emp_Salary) AS 'Sum of All Current Salaries'

    FROM
    (
    SELECT

        MAX(Emp_Salary_Change_Year) AS "Change Year"
        FROM Employee_Details AS e

    INNER JOIN Country AS co ON e.Emp_Country_Id = co.Country_Id
    INNER JOIN State AS s ON e.Emp_State_Id = s.State_Id
    INNER JOIN Designation AS d ON e.Desig_Id = d.Desig_Id
    INNER JOIN Salary AS sa ON e.Emp_Id = sa.Emp_Id
    WHERE Emp_Active = 1
    GROUP BY Emp_First_Name, Emp_Last_Name,
    Emp_Middle_Name, Country_Name, Desig_Name) AS C
    INNER JOIN Salary ON C.[Change Year] = Salary.Emp_Salary_Change_Year
    OPEN sumCurSalaryActiveEmps
    Fetch NEXT FROM sumCurSalaryActiveEmp
    INTO @sumCurSal

    WHILE @@FETCH_STATUS = 0
    BEGIN
        Fetch NEXT FROM sumCurSalaryActiveEmps 
            INTO @sumCurSal
            END
    close sumCurSalaryActiveEmps
    Deallocate sumCurSalaryActiveEmps

1 个答案:

答案 0 :(得分:0)

我同意所有说你不应该使用游标的人。当你真的需要一个时,它不到1%。但是,为了回答您的问题,这是一个可以用于光标的模板。

Declare sumCurSalaryActiveEmp Cursor Local Fast_Forward For
  -- Your select statement here.  For each column selected you need a corresponding variable to FETCH into

Open sumCurSalaryActiveEmp
Fetch Next From sumCurSalaryActiveEmp
  Into @sumCurSal -- YOU DECLARE These to match up to your select

While @@FETCH_STATUS = 0
  Begin
     -- Do your stuff here
    Fetch Next From sumCurSalaryActiveEmp 
      Into @sumCurSal
  End

Close sumCurSalaryActiveEmp
Deallocate sumCurSalaryActiveEmp

在您的特定代码中,您需要在OPEN语句之前删除关键字GO。