views:

31

answers:

1

I need to create a stored procedure one time and in one place only on my database server, but be able to run it from any database. However, I don't want to have to type database.schema.procedure_name every time I run it. I'd like to be able to use it like the built in procedures: sp_... is there any way to do this?

here is the procedure that I'm trying to create:

--actual procedure is more complex
CREATE PROCEDURE TestProcedure
AS

select * from sys.dm_exec_requests 

go

here is how I'd like to run it from SQL Server Management Studio:

EXEC TestProcedure
--or 
TestProcedure

however, you you get this error:

Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure 'TestProcedure'.

everything runs fine if I run it with:

EXEC master.dbo.TestProcedure
--or
master.dbo.TestProcedure

you can run system procedures like this without any errors:

EXEC sp_help
--or
sp_help
+5  A: 

Just create it in the master database and give it the sp_ prefix and it will work. SQL Server always checks the master database first for stored procedures (and other types of objects as well) with this prefix.

It will handle the datbase context for you as well as below.

USE master

create proc [dbo].[sp_test] as
select db_name()

GO

USE YourDB

EXEC master..sp_test  /*Returns "master"*/
EXEC sp_test          /*Returns "YourDB"*/

Edit:

Just following up Cade's comment to mark it as a system procedure. This seems like it might well be required in some circumstances. In SQL 2005+ you would use

EXEC sys.sp_MS_marksystemobject 'dbo.sp_test'
Martin Smith
Ken Henderson's Guru's Guide also mentions a need to set a system bit on some "user" system procedures to be able to call some DBCC things and stuff - not sure if this still applied post-SQL Server 2000, but I thought I'd add that as a comment.
Cade Roux
@Cade - I've found a link on Mladen Prajdić's blog that indicates it might still be needed in some cases. thanks!
Martin Smith