views:

915

answers:

4

Is there any way within a stored procedure for it to reference it's own name? Say I want it to print it's own name, but not to physically type the name in the stored procedure. Is there any cheater way to get the name or id from within the procedure itself without using the actual name to find the information?

+20  A: 

Try:

SELECT OBJECT_NAME(@@PROCID)

@@PROCID returns the object ID of the current SQL module. OBJECT_NAME translates an object ID to its name. Both are available from at least version 7 to 2008 of SQL Server.

David M
D'oh! Seconds too late. Touche! +1
Binary Worrier
+1 Works on my machine: By the way, does @@PROCID works for all versions of SQL Server? I mean, at least for SQL Server 2k/2k5/2k8?
Sung Meister
Yes, at least 2000 upwards. Can't remember whether this used to work on 6.5 or 7.
David M
+1: Perfect answer...answer comes quickly, followed by an clear explanation of what's going on.
Beska
Thanks. If anyone knows the answer for 7 and earlier, I'll happily edit further.
David M
+9  A: 

You're looking for @@PROCID and OBJECT_NAME i.e.

select @procName=OBJECT_NAME(@@PROCID)
Binary Worrier
No reason you shouldn't also get voted up for your answer just because you missed out by seconds.
TheTXI
Gents, I'm touched :)
Binary Worrier
+3  A: 

Name of proc/func

Select OBJECT_NAME(@@PROCID);

Other interesting stuff

 Select * From sys.sysprocesses Where spid = @@SPID
TFD
A: 

Here's some tinker code I wrote, running against a SQL Server 2005 database to play with the OBJECT_NAME(@@PROCID) function.

Run this section first, to create a log table

CREATE TABLE Diagnostics_Log 
  (
   sprocName sysname,
   WhenRun  datetime,
   Comment  Varchar(160) NULL
  )

--========================================

Then run this T-SQL to create a few versions of the same sproc, adding a numeric suffix each time.

CREATE PROC dg_test_name_logging
    @Comment Varchar(160)
AS 
  declare @Sprocname sysname
  select @sprocName = OBJECT_NAME(@@PROCID)

  PRINT @@PROCID
  print @sprocname

  insert into Diagnostics_Log VALUES (@sprocname, GetDate(), @Comment)

GO

--========== Then run this section

 exec dg_test_name_logging 'this is the first run'
WAITFOR DELAY '00:00:00:123'
  exec dg_test_name_logging1 'this is my second comment'
WAITFOR DELAY '00:00:00:123'
  exec dg_test_name_logging2 'yet another comment'
WAITFOR DELAY '00:00:02:123'
  exec dg_test_name_logging3 'amazing'
WAITFOR DELAY '00:00:00:123'
  exec dg_test_name_logging4 'I''ll be gobsmacked if this works'
WAITFOR DELAY '00:00:00:123'
  exec dg_test_name_logging5 'It''s ALIVE !!!'

  select * from Diagnostics_Log

Could be useful for logging when sprocs or views are run or accessed.

cometbill