PL/SQL procedure to kill inactive session

Hi all ,
Please i am trying to write a procedure to kill inactive sessions of the shema 'TESTSCHEMA' .This is my first procedure , am not use to pl/sql but i went through many turtorial but have some errors at compliation .when i try to compile the procedure the errors are as below :
15:50:28 Start Find Objects [TESTSCHEMA@TESTDB_UNIX(2)] ...
15:50:28 End Find Objects [TESTSCHEMA@ TESTDB_UNIX(2)]
15:50:32 Start Compiling 1 object(s) ...
15:50:32 Executing ALTER PROCEDURE fib_dead_cnx_cleanup COMPILE ...
15:50:32 [13:2] PL/SQL: ORA-00933: SQL command not properly ended
15:50:32 [9:3] PL/SQL: SQL Statement ignored
15:50:32 [18:12] PLS-00103: Encountered the symbol "(" when expecting one of the following:
15:50:32 constant exception <an identifier>
15:50:32 <a double-quoted delimited-identifier> table LONG_ double ref
15:50:32 char time timestamp interval date binary national character
15:50:32 nchar
15:50:32 The symbol "<an identifier>" was substituted for "(" to continue.
15:50:32 [18:21] PLS-00103: Encountered the symbol "LOOP" when expecting one of the following:
15:50:32 := ; not null default character
15:50:32 The symbol "; was inserted before "LOOP" to continue.
15:50:32 [27:8] PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:
15:50:32 begin case declare exit for goto if loop mod null pragma
15:50:32 raise return select update while with <an identifier>
15:50:32 <a double-quoted delimited-identifier> <a bind variable> <<
15:50:32 close current delete fetch lock insert open rollback
15:50:32 savepoint set sql execute commit forall merge pipe
15:50:32 Compilation complete - 5 error(s) found
15:50:32 End Compiling 1 object(s)
below is the procedure code :
CREATE OR REPLACE
PROCEDURE fib_dead_cnx_cleanup
AS
l_serial     CHAR(100);
l_sid CHAR (100);
l_sid_serial CHAR(100);
l_count      NUMBER(10,0);
CURSOR session_cur IS
          SELECT sid,serial#,sid||','||serial# as sid_serial
     FROM v$session
     WHERE username='EBBFCAT' and schemaname='TESTSCHEMA'
     and status='INACTIVE'
BEGIN
     BEGIN
     l_count := 0;
               OPEN session_cur;
                    WHILE ( 1 = 1) LOOP
                         BEGIN
                              FETCH session_cur INTO l_sid ,l_serial,l_sid_serial ;
                                   EXIT WHEN session_cur%NOTFOUND ;
                              BEGIN
                                   alter system kill session 'l_sid_serial' ;
                              END;     
                         END;
                    END;
               CLOSE session_cur;
     END;
END FIB_DEAD_CNX_CLEANUP;
Thanks

Hi,
Never write, let alone post, unformatted code.
When posting any formatted text on this site, type these 6 characters:
&#123;code&#125;
(small letters only, inside curly brackets) before and after sections of formatted text, to preserve spacing.
Among the benefits of formatting: you can indent to show the extent of blocks, such as BEGIN-END.
Different types of blocks need modifiers after the end, such as "END *IF* " and " END *LOOP* ". If each opening statement (BEGIN, IF, LOOP) is directly above its corresponding END, then it's easy to check if you got the right modifier.
Here's what you code looks like with some formatting, and a couple of corrections added. Look for -- comments.
CREATE OR REPLACE
PROCEDURE fib_dead_cnx_cleanup
AS
     l_serial     CHAR(100);
     l_sid          CHAR (100);
     l_sid_serial     CHAR(100);
     l_count          NUMBER(10,0);
     CURSOR session_cur IS
            SELECT  sid
            ,       serial#
            ,       sid     || ','
                                  || serial#     as sid_serial
            FROM     v$session
            WHERE      username     = 'EBBFCAT'
            and     schemaname     = 'TESTSCHEMA'
            and     status          = 'INACTIVE';          -- need semicolon here
BEGIN
     BEGIN                                   -- Why?
          l_count := 0;
          OPEN session_cur;
          WHILE ( 1 = 1)
          LOOP
                BEGIN                         -- Why?
                     FETCH  session_cur
                     INTO   l_sid
                     ,          l_serial
                     ,          l_sid_serial ;
                           EXIT WHEN session_cur%NOTFOUND ;
                     BEGIN                    -- Why?
                         alter system kill session 'l_sid_serial' ;    -- Not a PL/SQL command
                           END;
                      END;
            END LOOP;                         -- LOOP ends with END LOOP
            CLOSE session_cur;
        END;
END      FIB_DEAD_CNX_CLEANUP;Take baby steps.
I've been wrtiing PL/SQL for 20 years, and I would never write that much code at once. If you're a beginner, all the more reason to start small. Write as little as possible, test, debug and test again (if necessary). When you have someting working, add 2 or 3 more lines and test again.
It looks like you have three BEGIN statements that don't serve any purpose. You should get rid of them (and their corresponding END statements, of course).
One error I did not fix: ALTER SYSTEM is not a PL/SQL statement. It's a SQL statement. You can run a SQL statement inside PL/SQL by using dynamic SQL, where you construct a string containing the SQL statement, and then use dbms_sql or EXECUTE IMMEDIATE to run it.
Edited by: Frank Kulash on Aug 18, 2009 12:37 PM

Similar Messages

  • AUTOMATICALLY KILL  INACTIVE SESSIONS

    Hi all. we are using oracle 8.1.6 on windows-2000 with 2gb ram. we facing
    ora-12500 listner failed to start a dedicated server.
    error and for this we made certain changes. we also added a parameter in sqlnet.ora at server side sqlnet.expire_time=10.. for automatically killing inactive sessions but it did not helped and many sessions remain in v$session. i wana know what should we do to kill inactive sessions. because i think when the sessions reach more than 300 then we face problem of listner failed. thanks for u'r valueable comments in advance as well.
    best wishes
    muhammad mohsin chattha

    Hi Nicolas, what you say is correct, but, unless the user try to do something (and receives an error),
    those sessions will show up as SNIPED in V$SESSION, and never go away.
    We can create a procedure to kill these sessions, something like this :  1  CREATE OR REPLACE PROCEDURE Kill_Sessions   IS
      2      Stmt           VARCHAR2(200);
      3      V_Sid          VARCHAR2(30);
      4      V_Serial       VARCHAR2(30);
      5      V_Username     VARCHAR2(30);
      6      CURSOR pri IS
      7      SELECT Sid, Serial#, Username
      8      FROM V$Session
      9      WHERE Username Is Not Null
    10      And Username not like 'SYS%'
    11      And Status = 'SNIPED';
    12  BEGIN
    13      FOR usr in pri LOOP
    14      V_Sid     := usr.Sid;
    15      V_Serial  := Usr.Serial#;
    16      Stmt      := 'ALTER SYSTEM KILL SESSION ''' || V_Sid || ',' || V_Serial || '''';
    17      Execute Immediate(Stmt);
    18      END LOOP;
    19* END;
    20  /  and execute it every minute (change 1440 to change the frequence) :SQL> Declare
      2     Out_Var Int;
      3  Begin
      4     Dbms_Job.Submit(Out_Var,
      5     'Kill_Sessions;',
      6     Sysdate,
      7     'Sysdate+1/1440' );
      8* End;
    SQL> /
    PL/SQL procedure successfully completed.
    SQL> commit;
    Commit complete.
    SQL>

  • Procedure to kill a session

    I do not have priviledge to kill the session, and i have checked the forums to create a procedure to kill the session,
    so how can i use that procedure to kill the session.
    Thanks

    If you should be allowed to kill sessions, then your DBA will grant you the ALTER SYSTEM privilege. Or, you could request your DBA to create a stored procedure for it and then grant you execute permission on that procedure. Of course, if your DBA does not choose to do this, then this is a discussion you should be having with your management.

  • Kill Inactive Sessions

    There are a lot of inactive sessions in my server, and I want to make a procedure to kill.But I can not use command like 'alert system kill session ...' in the procedure.
    How can I do it.

    Hi,
    Use the dbms_sql package to do the job.
    procedure(v_sid varchar2, v_serial varchar2);
    c number;
    n number;
    ssql varchar2(1000);
    begin
    c:=dbms_sql.open_cursor;
    sqlstr:='alter system kill session '&#0124; &#0124;
    ''''&#0124; &#0124;v_sid&#0124; &#0124;', '&#0124; &#0124;v_serial&#0124; &#0124;''''&#0124; &#0124;';';
    dbms_sql.parse(c, ssql, dbms_sql.native);
    n:=dbms_sql.execute(c);
    dbms_sql.close_cursor(c);
    end;
    null

  • Kill inactive sessions with no programs run it

    hi all,
    my database is 10gR2 with developer 6i
    the database have huge number of sessions with no programs running it like oracle form, some of those sessions stack in v$session table due to power failure.
    restart server solve the problem, but it is not efficient.
    is there any method to fined witch of database sessions is actually connect to the database and have application running it ?

    This script will give you the complete detail of Session , PID and Program which is running in dagtabase level.
    You can include the "STATUS" coloumn from v$session to get user status.
    Script is like this:
    set echo off;
    set termout on;
    set linesize 80;
    set pagesize 60;
    set newpage 0;
    select
    rpad(c.name||':',11)||rpad(' current logons='||
    (to_number(b.sessions_current)),20)||'cumulative logons='||
    rpad(substr(a.value,1,10),10)||'highwater mark='||
    b.sessions_highwater Information
    from
    v$sysstat a,
    v$license b,
    v$database c
    where
    a.name = 'logons cumulative'
    ttitle "dbname Database|UNIX/Oracle Sessions";
    set heading off;
    select 'Sessions on database '||substr(name,1,8) from v$database;
    set heading on;
    select
    substr(a.spid,1,9) pid,
    substr(b.sid,1,5) sid,
    substr(b.serial#,1,5) ser#,
    substr(b.machine,1,6) box,
    substr(b.username,1,10) username,
    -- b.server,
    substr(b.osuser,1,8) os_user,
    substr(b.program,1,30) program
    from v$session b, v$process a
    where
    b.paddr = a.addr
    and type='USER'
    order by spid;
    ttitle off;
    spool off;
    Save this script with your desire name and run in Database.
    Mukesh

  • Killing inactive and disconnected sessions

    hi all
    how can i kill inactive sessions from server, can someone provide me query for both selecting and killing inactive sessions.
    Thanks in advance.
    piyush

    There is no valid reason for killing a session simply because it is INACTIVE. It is plain wrong. Bad DBA'ing. Silly.. Clueless.. etc.
    The correct approach is to IDENTIFY the problem (e.g. too many dedicated server connections for the db platform to handle) and then the solution (e.g. using shared server).
    Simply identifying and killing idle sessions? That is fighting a symptom. It is not fixing a problem.

  • About Inactive Sessions

    Hello everybody:
    I need some help, this is my situation:
    Every day when I arrive to my job I have to kill inactive session from other days, e.g Today I had to kill a lot of Inactive Session of Yesterday.
    How could I did this by other way.
    Thanks

    Hiow are you determining that the session is inactive? If you are only looking at v$session.status then be aware that you cannot determine if a session is truely INACTIVE from this column alone. You must also look at last_call_et.
    The reason is that Oracle only considers a session ACTIVE while it is processing SQL (or pl/sql) and with a dedicated session and a connect pooled front-end or a client like Forms where the user spends a lot of time filling in the screen or reviewing results then while you see an INACTIVE status in two queries of v$session 30 seconds apart while the session may have run 8 fast short SQL statements in between your viewing v$session. The last_call_et column woud reflect the activity but it is unlikely you would catch the ACTIVE status.
    HTH -- Mark D Powell --

  • Inactive sessions increasing database

    Hi
    We are using oracle11.5.10.2 on windows 2000 server and database version 10.2.0.3
    we are facing problem with inactive sessions,grdually inactive sessions increasing and thats leads database crash.
    Temporary i increased processes parameter value tp 400 prviously it was 200
    Most of inactive session from apps user only
    How can i fix this problem?
    Thanks
    With Regards
    OH

    Hi,
    Please see these threads.
    how to kill inactive sessions????????
    how to kill inactive sessions????????
    Inactive sessions in Database
    Re: Inactive sessions in Database
    Regards,
    Hussein

  • Procedure that kill session....

    Hello folks,
    how can i write a procedure that provoque the sql statment alter system kill session'159,554' immediate;
    i put it as it is in a pl/sql block but it gave error....
    please advise........

    Something like this ?
    SYS@db102 SQL> create or replace procedure killproc (
      2     sid_in          number,
      3     serial_in       number)
      4  is
      5  begin
      6     execute immediate ('alter system kill session '||chr(39)||sid_in||','||serial_in||chr(39));
      7* end;
    SYS@db102 SQL> /
    Procedure created.
    SYS@db102 SQL> select username,sid,serial#,status from v$session
      2  where username is not null;
    USERNAME                              SID    SERIAL# STATUS
    SYS                                   145        124 ACTIVE
    TEST                                  148         87 INACTIVE
    SYS@db102 SQL> exec killproc(148,87);
    PL/SQL procedure successfully completed.
    SYS@db102 SQL> select username,sid,serial#,status from v$session
      2  where username is not null;
    USERNAME                              SID    SERIAL# STATUS
    SYS                                   145        124 ACTIVE
    TEST                                  148         87 KILLED
    SYS@db102 SQL>                                                            

  • Kill the session Using Pl/sql Script

    Hi,
    I wrote a PL/SQL Script which kills the Specified Schema name..... the Script Run Successfully i got this output message "PL/SQL procedure successfully completed." But the Problem is in session status the status is in KILLED" state for more than 30 minutes.
    Please Advice Why the Session in Killed State for more than 30 minutes and please tell me how to kill the session immediate;
    I am Using Oracle DB 11g R1 and OS is Windows 2003 Server R2
    My Pl/sql Script
    SET SERVEROUTPUT ON;
    DECLARE
    KILLER1 V$SESSION.SID%TYPE;
    KILLER2 V$SESSION.SERIAL#%TYPE;
    CURSOR KILL_SESSION IS SELECT SID,SERIAL# FROM V$SESSION WHERE SCHEMANAME='NAME';
    BEGIN
    OPEN KILL_SESSION;
    LOOP
    FETCH KILL_SESSION INTO KILLER1,KILLER2;
    EXIT WHEN KILL_SESSION%NOTFOUND;
    DBMS_OUTPUT.put_line ('ALTER SYSTEM KILL SESSION '''||KILLER1||','||KILLER2||''' IMMEDAITE');
    EXECUTE IMMEDIATE 'ALTER SYSTEM KILL SESSION'||chr(39)||KILLER1||','||KILLER2||chr(39);
    END LOOP;
    IF (KILLER1 > 0)
    THEN
    EXECUTE IMMEDIATE 'ALTER SYSTEM KILL SESSION'||chr(39)||KILLER1||','||KILLER2||chr(39);
    END IF;
    CLOSE KILL_SESSION;
    END;
    Thank You
    Shan

    Hello,
    In fact you may use orakill it's an Oracle utility for Windows so as to Kill the thread corresponding
    to the session.
    It's equivalent to a kill -9 on Unix.
    Please find here a link about the use of orakill:
    http://articles.techrepublic.com.com/5100-10878_11-5224960.html
    Hope this help.
    Best regards,
    Jean-Valentin
    Edited by: Lubiez Jean-Valentin on Mar 27, 2010 5:17 PM

  • Procedure for Killing sessions

    Hi All,
    Almost everyday we have requirement to kill user sessions for dev user, I'm thinking to create a procedure for this and grant to the users so that they can kill it by themself.
    Below is the what I got from Ask Tom forum, however appreciate if someone can share few information if already imlemented in there environment
    <quote>
    create or replace procedure kill_session( p_sid in number,
    p_serial# in number)
    is
    ignore pls_integer;
    BEGIN
    select count(*) into ignore
    from V$session
    where username = USER
    and sid = p_sid
    and serial# = p_serial# ;
    if ( ignore = 1 )
    then
    execute immediate '
    alter system kill session ''' ||
    to_char(p_sid,'999999')||','||
    to_char(p_serial#,'999999')||'''';
    else
    raise_application_error( -20001,
    'You do not own session ''' ||
    p_sid || ',' || p_serial# ||
    end if;
    END;/
    grant execute on kill_session to <username>
    </quote>
    Regards,
    shaan

    rp0428 wrote:
    >
    Instead of killing session with alter systemn kill session, better you opt for below two methods (still perform the same)
    >
    Please clarify what you mean. KILL and DISCONNECT do NOT perform the same.
    From the SQL Language doc
    http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_2013.htm
    KILL is the nice one -
    >
    The KILL SESSION clause lets you mark a session as terminated, roll back ongoing transactions, release all session locks, and partially recover session resources
    >
    While DISCONNECT is the ogre
    >
    Use the DISCONNECT SESSION clause to disconnect the current session by destroying the dedicated server process (or virtual circuit if the connection was made by way of a Shared Sever).
    >
    The difference between the two is roughly analogous to the difference between SHUTDOWN IMMEDIATE and SHUTDOWN ABORT.
    I agree that, for OPs use case DISCONNECT (with IMMEDIATE or POST TRANSACTION) may be better since it gets rid of things immediately while KILL can leave things hanging around for a while.From the same link:
    DISCONNECT SESSION Clause:
    The POST_TRANSACTION setting allows ongoing transactions to complete before the session is disconnected. If the session has no ongoing transactions, then this clause has the same effect described for as KILL SESSION.
    The IMMEDIATE setting disconnects the session and recovers the entire session state immediately, without waiting for ongoing transactions to complete.
    If you also specify POST_TRANSACTION and the session has ongoing transactions, then the IMMEDIATE keyword is ignored.
    If you do not specify POST_TRANSACTION, or you specify POST_TRANSACTION but the session has no ongoing transactions, then this clause has the same effect as described for KILL SESSION IMMEDIATE.
    basically the difference is not between DISCONNECT and KILL SESSION, the difference exists if you allow pending/ongoing transactions to finish(IMMEDIATE vs POST_TRANSACTION)
    Edited by: Keilor on Jun 25, 2012 12:57 PM
    Edited by: Keilor on Jun 25, 2012 1:39 PM

  • Kill user sessions dynamically through PL/SQL

    Hello,
    Every night I have to DROP one user in order to recreate the entire schema. In order to do this I have to disconnect the user from the DB by killing its sessions. I am using following PL/SQL code
    ALTER SYSTEM ENABLE RESTRICTED SESSION;
    begin
        for x in (
                select Sid, Serial#, machine, program
                from v\$session
           where username = 'STARSTAGING_DB'
       ) loop
              execute immediate 'Alter System DISCONNECT Session '''|| x.Sid
                      || ',' || x.Serial# || ''' IMMEDIATE';
        end loop;
    end;
    DROP USER starstaging_db CASCADE;
    ALTER SYSTEM DISABLE RESTRICTED SESSION;
    I have also tried using keyword KILL instead of DISCONNECT of session.
    Most of the day this works, user is dropped and new one is created, but sometimes I get the following problem.
    The problem that has occurred in a log file is:
    PL/SQL procedure successfully completed.
    DROP USER starstaging_db CASCADE
    ERROR at line 1:
    ORA-01940: cannot drop a user that is currently connected
    System altered.
    CREATE USER STARSTAGING_DB IDENTIFIED BY *****
    ERROR at line 1:
    ORA-01920: user name 'STARSTAGING_DB' conflicts with another user or role name
    Does anyone have an idea how I can make sure that the user for sure disconnects, so that I can drop him?
    Best Regards,
    Vladimir

    Cannot comment on a better approach as that means a proper analysis of the business requirements. Just keep in mind that killing sessions is a brutal way to manage user connectivity to the database - and should be seen as an exception and the last resort.
    You can wrap your schema drop code into a retry loop. Something as follows:
    loop
       begin
          ..do the drop..
          success := true;
      exception when FAILED then
          dbms_lock.sleep(60); -- sleep 60 seconds
      end;
      retry := retry + 1;
      exit when success or retry > HAVE_WAITED_LONG_ENOUGH;
    end loop;

  • Cannot kill a session that is running a query on a linked server in SQL Server 2008 R2

    Hi,
    Cannot kill a session that is running a query on a linked server  in SQL Server 2008 R2.
    When I try to kill, it status shown as "KILLED/ROLLBACK"
    I have facing the issue from long back. I searched many and none of them worked for me
    Any help is greatly appreciated
    Thanks
    Jaison
    Carver

    I guess its stuck, can you see some blocking or any other process blocking the rollback.
    can you check rollback status using below command. Or you can use sp_who2 and check status column
    select percent_complete,estimated_completion_time from sys.dm_exec_requests
    where spid=xxx
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it.
    My TechNet Wiki Articles

  • How to kill a  session in stored procedure or trigger.

    Can anyone let me know, how to kill a particular session in stored procedure or trigger.
    Regards
    KVSS

    also you cannot attempt to kill ur own current session.
    But on what circumstances you want to kill the session.
    When anyone trys to access a table and lets suppose the trigger onthat table activates
    and you want to kill that very session which activated the trigger ???
    i dont think its possible. To kill a session definitely you should be in a different session and
    then only you can achieve that.
    pls check it out
    prakash
    [email protected]

  • Kill DBA session feature in SQL Developer

    Hi All,
    Like in TOAD , we have a Kill/DBA session option is on toolbar and we can easily trace down the sessions running as well as SID and serial number ..... Do We have similar feature on SQL Developer ?
    Currently my SQL Developer version is 1.0.0.14.67 and Build Main 14.67

    it's in sqldev 1.1 (in reports/database administration/sessions/sessions)

Maybe you are looking for

  • "Application system preferences quit unexpectedly" Error message

    This is the message that I get when I try to open the destop and screensavers part of the system preferences. It also does a similar thing when I open photoshop and press command+O to open a file but not when I right click a file and open it in photo

  • Failover, load balancing, band sharing - problem

    I would like to accomplish the following task: SW-A and SW-B two separate subnets, without any contact with each other. 1. Router A would perform as a gateway for computers connected to SW-A 2. Router B would perform as a gateway for computers connec

  • M55 Windows 7 Home Premium 64 bit

    I recently upgraded my m55 8810-94U from Windows XP Professional to Windows 7 Home Premium.  Upgrade went fine, system boots to Windows 7.  Shortly after  launching any program, my monitor goes black and loses signal.  The actually system is still on

  • Error while installing "instantclient-sqlplus-linux32-11.2.0.1.zip"  linux

    I have a linux box where i just need the oracle client/sqlplus to connect to database. So I downloaded "instantclient-sqlplus-linux32-11.2.0.1.zip" and unzipped it in a directory.It has the following files -r--r--r-- 1 root deploy 342 Aug 13 21:15 gl

  • ITunes 10.5.0.142 reboot my NAS

    Hi, I use a NAS WD ShareSpace like iTunes library storage not like an iTunes server. Before iTunes version 10.5.0.142 all was perfect. But after this update, when I try to obtain thru iTunes some information about an mp3 file stored in my NAS, NAS re