Cursors :
Synatx :
Declare cursor Cursor_Name Cursor_Type for (Query)
Open Cursor
fetch next from Cursor_Name
--Statements--
CLOSE Cursor_Name
DEALLOCATE Cursor_Name
Example: get the Employee names started with 'K'
DECLARE @Emp_ID varchar(20),@Emp_Name varchar(20),
@message varchar(max);
PRINT '-------- EMPLOYEE DETAILS --------';
DECLARE emp_cursor CURSOR FOR
SELECT Emp_ID,Emp_Name
FROM Employee_information_master
order by convert(int ,substring(Emp_ID,5,len(Emp_ID)));
OPEN emp_cursor
FETCH NEXT FROM emp_cursor
INTO @Emp_ID,@Emp_Name
print 'Employee_ID | Employee_Name'
WHILE @@FETCH_STATUS = 0
BEGIN
if (@Emp_Name like '%K')
begin
print ' ' + CAST(@emp_id as varchar(10)) +' '+ cast(@emp_name as varchar(20))
end
FETCH NEXT FROM emp_cursor
INTO @emp_id,@emp_name
END
CLOSE emp_cursor
DEALLOCATE emp_cursor
No comments:
Post a Comment