2016-11-07 35 views
2

我有一個像下面如何在sql server 2008中聲明時使用光標條件?

Declare Cur_1 cursor for 

     if @EmployeeId <> is not null 
      begin 
       select EmployeeID from tbl_Employee where EEmployeeStatus='Active' and EmployeeID = @EmployeeId 
      end 
     else 
      begin 
       select EmployeeID from tbl_Employee where EEmployeeStatus='Active' 
      end 

Open Cur_1 

    Fetch next from Cur_1 into @EmpId 
    While @@FETCH_STATUS=0 
    Begin 

    end 
Close Cur_1 
deallocate Cur_1 

查詢,但它不工作。它顯示我的語法錯誤。

它顯示語法錯誤,如果條件..

請幫我.......

+1

'如果@EmployeeID不null',就沒有必要對<> – Zeina

回答

1
if @Feild is not null 
     begin 
      Declare your_Cursor_Name cursor for  
        select Feild1 from Your_table where 1=1 
     end 
    else 
     begin 
      Declare your_Cursor_Name cursor for  
        select Feild1 from Your_table where 1=1 
     end 

    Open your_Cursor_Name 

     Fetch next from your_Cursor_Name into @xyz 
     While @@FETCH_STATUS=0 
     Begin 
      `enter code here 
     end 
Close your_Cursor_Name 
+0

也許你需要解釋一下你的回答代碼 – Zeina

+1

當然..下次我在乎這個...謝謝你 – Deepak

2

的Corrrect語法必須是:if @EmployeeId is not null

沒有必要<>前不是null,因爲is是這裏的運營商。

1

,請不要使用,如果建設光標內,而不是有兩個可能的聲明:

if @EmployeeId is not null 
     begin 
      Declare Cur_1 cursor for  
        select EmployeeID from tbl_Employee where EEmployeeStatus='Active' and EmployeeID = @EmployeeId 
     end 
    else 
     begin 
      Declare Cur_1 cursor for  
        select EmployeeID from tbl_Employee where EEmployeeStatus='Active' 
     end 

    Open Cur_1 

     Fetch next from Cur_1 into @EmpId 
     While @@FETCH_STATUS=0 
     Begin 

     end 
    Close Cur_1 
    deallocate Cur_1