Dhaval Purohit Dhaval Purohit - 28 days ago 9
SQL Question

how to use if condition in cursor at time of declaration in sql server 2008?

I have query like below

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


but it's not working. it's show me syntax error.

it's show syntax error in if condition..

please help me.......

Answer
 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 
Comments