Db/Mssql

mssql cursor sample

seongsland 2011. 11. 21. 14:16


CREATE FUNCTION [dbo].[GET_DEPT_LIST](@p_dept_id VARCHAR(40))
RETURNS @deptList TABLE
(
  dept_id varchar(20),
  dept_name varchar(100),
  dept_level int
)
AS
BEGIN
 DECLARE @deptId   VARCHAR(20)
 DECLARE @deptName   VARCHAR(100)
 DECLARE @deptLevel   int

 DECLARE C_LIST CURSOR
    FOR
    with dept_list(dept_id, dept_name, dept_level) as (
   select dept_id, dept_name, 0 as dept_level
   from department
   where dept_id=@p_dept_id
   union all
   select a.dept_id, a.dept_name, b.dept_level+1
   from department as a
     join
     dept_list b
   on a.parent_dept_id=b.dept_id
  )
  select dept_id, dept_name, dept_level from dept_list

  OPEN C_LIST   -- cursor open
        FETCH NEXT FROM C_LIST INTO @deptId, @deptName, @deptLevel

        WHILE @@FETCH_STATUS = 0
        BEGIN
   insert @deptList values(@deptId, @deptName, @deptLevel)
           
            FETCH NEXT FROM C_LIST INTO @deptId, @deptName, @deptLevel
        END

   CLOSE C_LIST
    DEALLOCATE C_LIST
 
 return
END