Monday, 5 November 2012

Cursors in sql server


--First example
  select * from Employee
  DECLARE samplecursor CURSOR for select emp_no from Employee
  DECLARE @emp_no int
  open samplecursor
  FETCH NEXT FROM samplecursor into @emp_no
  while @@FETCH_STATUS=0
  BEGIN
  print @emp_no
  fetch next from samplecursor into @emp_no
  END
  CLOSE samplecursor
  --second example
   DECLARE SECONDCURSOR123 CURSOR FOR select emp_fname from Employee
   DECLARE @emp_fname varchar(50)
   open SECONDCURSOR123
   FETCH NEXT FROM SECONDCURSOR123 INTO @emp_fname
   WHILE @@FETCH_STATUS=0
   BEGIN
   PRINT @emp_fname
   FETCH NEXT FROM SECONDCURSOR123 into @emp_fname
   END
   CLOSE SECONDCURSOR123
   select * from EmployeeDummy sys.all_objects where type='u'
   --cursor Examples
   DECLARE CURSOR_EXAMPLE CURSOR FOR select emp_no from EmployeeDummy
   DECLARE @Employeeno int
   open CURSOR_EXAMPLE
   FETCH NEXT FROM CURSOR_EXAMPLE into @Employeeno
   WHILE @@FETCH_STATUS=0
   BEGIN
   PRINT @Employeeno
   FETCH NEXT FROM CURSOR_EXAMPLE
   END
   CLOSE CURSOR_EXAMPLE
 
 
   select * from dbo.EMPJOB
   DECLARE AVUSAL_CURSOR CURSOR FOR SELECT averagesalary from EMPJOB
   DECLARE @Avgsalary int
   open AVUSAL_CURSOR
   FETCH NEXT FROM AVUSAL_CURSOR
   WHILE @@FETCH_STATUS=0
   BEGIN
   PRINT @Avgsalary
   FETCH NEXT FROM AVUSAL_CURSOR
   END
   CLOSE AVUSAL_CURSOR
 
   select * from Employee
 
   --ksn
   DECLARE CURSOR_EMPLOYEE CURSOR FOR SELECT emp_no,emp_fname from Employee
   DECLARE @empno int,@emp_name varchar(50)
   open CURSOR_EMPLOYEE
   FETCH NEXT FROM CURSOR_EMPLOYEE INTO @empno,@emp_name
   WHILE @@FETCH_STATUS=0
   BEGIN
   PRINT 'empno'+@empno+'empname'+@emp_name
   FETCH NEXT FROM CURSOR_EMPLOYEE
   END
   CLOSE CURSOR_EMPLOYEE

No comments:

Post a Comment