Returns the object identifier (ID) of
the current Transact-SQL module. A
Transact-SQL module can be a stored
procedure, user-defined function, or
trigger.
You can check for NULL before getting the schema and name of the stored procedure.
This means that you can get the right data even for (global) temporary stored procedures (click image to make bigger):
USE [master]; --so we can test temp sprocs without cheating by being in tempdb.
GO
BEGIN TRAN;
GO
CREATE PROC dbo.NotTempProc
AS
BEGIN
SELECT CASE
WHEN OBJECT_SCHEMA_NAME(@@PROCID) IS NULL
THEN OBJECT_SCHEMA_NAME(@@PROCID, 2) + N'.' + OBJECT_NAME(@@PROCID, 2)
ELSE OBJECT_SCHEMA_NAME(@@PROCID) + N'.' + OBJECT_NAME(@@PROCID)
END AS ProcName;
END
GO
EXEC dbo.NotTempProc;
GO
CREATE PROC dbo.#TempProc
AS
BEGIN
SELECT CASE
WHEN OBJECT_SCHEMA_NAME(@@PROCID) IS NULL
THEN OBJECT_SCHEMA_NAME(@@PROCID, 2) + N'.' + OBJECT_NAME(@@PROCID, 2)
ELSE OBJECT_SCHEMA_NAME(@@PROCID) + N'.' + OBJECT_NAME(@@PROCID)
END AS ProcName;
END
GO
EXEC dbo.#TempProc;
GO
CREATE PROC dbo.##GlobalTempProc
AS
BEGIN
SELECT CASE
WHEN OBJECT_SCHEMA_NAME(@@PROCID) IS NULL
THEN OBJECT_SCHEMA_NAME(@@PROCID, 2) + N'.' + OBJECT_NAME(@@PROCID, 2)
ELSE OBJECT_SCHEMA_NAME(@@PROCID) + N'.' + OBJECT_NAME(@@PROCID)
END AS ProcName;
END
GO
EXEC dbo.##GlobalTempProc;
GO
ROLLBACK;