/* Procedure copyright(c) 1996 by Edward Barlow */

:r database
go
:r dumpdb
go

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

create procedure sp__lock( @dbname char(30)=null,@spid smallint=null )
as
begin

declare @dbid smallint
if @dbname is not null
	select @dbid=db_id(@dbname)

	select   
				"Type"=substring(v.name,1,11),
				"Usernm"=substring(suser_name(p.suid)+" (pid="+rtrim(convert(char(3),l.spid))+")",1,18),
				"TableNm"=convert(char(22),db_name(l.dbid)+".."),
				"Page"=convert(char(8),l.page),
				"Cmd"=substring(p.cmd,1,11),
				l.id,
				l.dbid
	into  	#locks
	from     master..syslocks l,
				master..sysprocesses p,
				master..spt_values v
	where    p.spid=l.spid
		and   l.type = v.number
		and   v.type = "L"
		and	p.dbid=isnull(@dbid,l.dbid)
		and	l.spid=isnull(@spid,p.spid)


	update #locks
	set	TableNm=TableNm+object_name(id)
	where dbid=db_id() 

	update #locks
	set	TableNm=TableNm+name
	from  #locks l, master..sysobjects o
	where l.dbid=1 
	and	l.id = o.id

	update #locks
	set   TableNm=TableNm+convert(varchar,id)
	where dbid<>db_id() and dbid>1

	delete #locks
	where TableNm like "tempdb..#locks%"

	select Type, "User"=Usernm, "Table"=TableNm, Page, Cmd
	from #locks
	order by dbid, id, Type

	return 0
end
go

grant execute on sp__lock to public
go
