是否可以获取MS SQL Server中当前存储过程的名称?
也许有系统变量或函数之类的GETDATE()
?
是否可以获取MS SQL Server中当前存储过程的名称?
也许有系统变量或函数之类的GETDATE()
?
Answers:
OBJECT_SCHEMA_NAME(@@PROCID) + '.' + OBJECT_NAME(@@PROCID)
BEGIN TRAN GO CREATE PROC utility.TempProc AS SELECT OBJECT_SCHEMA_NAME(@@PROCID)+'.'+OBJECT_NAME(@@PROCID) GO EXEC utility.TempProc GO ROLLBACK GO BEGIN TRAN GO CREATE PROC utility.#TempProc AS SELECT OBJECT_SCHEMA_NAME(@@PROCID)+'.'+OBJECT_NAME(@@PROCID) GO EXEC utility.#TempProc GO ROLLBACK GO
返回当前Transact-SQL模块的对象标识符(ID)。Transact-SQL模块可以是存储过程,用户定义的函数或触发器。
在特定情况下,如果您对当前正在执行的临时存储过程的名称感兴趣,则可以通过以下方式获取它:
select name
from tempdb.sys.procedures
where object_id = @@procid
您不能在SQL Server中使用接受的答案来查找当前正在执行的临时存储过程的名称:
create procedure #p
as
select object_name(@@PROCID) as name
go
exec #p
name
--------------------------------------------------------------------------------------------------------------------------------
NULL
(1 row affected)
您可以NULL
在获取存储过程的模式和名称之前进行检查。
这意味着即使对于(全局)临时存储过程,您也可以获得正确的数据(单击图像放大):
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;