Aug 9, 2011

Simple Cursor in Sql Sqerver/ How to use cursor in MS Sql Server

ALTER PROCEDURE Usp_removrights @userList   VARCHAR(MAX),
                                @menu       SMALLINT,
                                @submenu    SMALLINT,
                                @subsubmenu SMALLINT
AS
  DECLARE @count INT

  SET @count=0

  DECLARE @user_no VARCHAR(MAX)
  DECLARE @user_id VARCHAR(MAX)

  BEGIN TRY
      --Find out the cursors that are opened and not close
      SELECT @count = COUNT(*)
      FROM   sys.Dm_exec_cursors(0)
      WHERE  is_open = 1
             AND name = 'cur_RemovRight'

      IF ( @count > 0 )
        BEGIN
            CLOSE cur_removright;

            DEALLOCATE cur_removright;
        END

      DECLARE cur_removright CURSOR FOR
        SELECT VALUE
        FROM
dbo.Split('00011 ,00261 , 01014 , 01019 ,  01022 ,  80011 ,  80012 ,  80013 ,  80014 ', ',')

    OPEN cur_removright

    FETCH NEXT FROM cur_removright INTO @user_no;

    WHILE @@FETCH_STATUS = 0
      BEGIN
          SELECT @user_id = muser_userid
          FROM   infoview
          WHERE  muser_empno = @user_no

          INSERT INTO userlevelrights1
                      (userid,
                       menu,
                       submenu,
                       subsubmenu)
          VALUES     (@user_id,
                      @menu,
                      NULL,
                      NULL)

          PRINT @user_id

          --Delete from userlevelrights1 where userid=@user_id
          FETCH NEXT FROM cur_removright INTO @user_no;
      END

    CLOSE cur_removright;

    DEALLOCATE cur_removright;
END TRY

  BEGIN CATCH
      INSERT INTO errorlog_sp
      SELECT Error_number()    AS errornumber,
             Error_severity()  AS errorseverity,
             Error_state()     AS errorstate,
             Error_procedure() AS errorprocedure,
             Error_line()      AS errorline,
             Error_message()   AS errormessage,
             Getdate()

      RAISERROR ('Error catch',
                 10,
                 1)
  END CATCH 

No comments:

Post a Comment

What is the use of n-tier architecture and 3-tier architecture?

how to implement 3-tier architecture in asp.net using c#. 3-Tier architecture is also called layered architecture. Some people called it ...