/* Procedure copyright(c) 1993-1995 by Ed Barlow */
/* Copied from sp__whodo by simon walker */

:r database
go
:r dumpdb
go

if exists (select * 
         from   sysobjects 
         where  type = 'P'
         and    name = "sp__whodo")
begin
    drop procedure sp__whodo
end
go

create procedure sp__whodo (@parm varchar(30) = null) 
as
begin
    declare @parmsuid int , @parmdbid int
 
    if @parm is not NULL 
    begin

        select @parmsuid = suser_id(@parm)
        if @parmsuid is NULL
        begin
			   select @parmdbid = db_id(@parm)
			   if @parmdbid is null
			   begin
               print "No login exists with the supplied name."
               return (1)
			   end
        end

        select pid = convert(char(3), spid),
           loginame= substring(suser_name(suid), 1, 9),
	   		"cpu" = convert(char(5),cpu%10000),
	   		"io"  = convert(char(5),physical_io%10000),
	   		"mem" = convert(char(5),memusage%10000),
           dbname = substring(db_name(dbid), 1, 10),
           status = convert(char(8), status),
           cmd,
           bk = convert(char(2), blocked),
	        bktime=convert(char(4),-1)
        from   master..sysprocesses
        where cmd != "AWAITING COMMAND"
	     and	  cmd != "NETWORK HANDLER"
	     and	  cmd != "MIRROR HANDLER"
	     and	  cmd != "AUDIT PROCESS"
	     and	  cmd != "CHECKPOINT SLEEP"
		  and   isnull(@parmdbid,dbid) = dbid
		  and	  isnull(@parmsuid,suid) = suid
    end
	 else
    select pid = convert(char(3), spid),
           loginame= substring(suser_name(suid), 1, 9),
	   		"cpu" = convert(char(5),cpu),
	   		"io"  = convert(char(5),physical_io),
	   		"mem" = convert(char(5),memusage),
           dbname = substring(db_name(dbid), 1, 10),
           status = convert(char(8), status),
           cmd,
           bk = convert(char(2), blocked),
	   bktime=convert(char(4),-1)
    from   master..sysprocesses
    where  cmd != "AWAITING COMMAND"
	 and	  cmd != "NETWORK HANDLER"
	 and	  cmd != "MIRROR HANDLER"
	 and	  cmd != "AUDIT PROCESS"
	 and	  cmd != "CHECKPOINT SLEEP"

    return
end
go

grant execute on sp__whodo to public
go
