如何获取当前存储过程名称?能否用变量简化存储过程测试注释?
Great question! Let's break this down into two clear parts to address your needs:
1. Is /* EXEC @thisStoredProceduresName */ possible in comments?
Unfortunately, no. SQL treats comments as static, unparsed text—any variables or expressions inside comments won't be evaluated or replaced. Writing @thisStoredProceduresName in a comment will just stay as plain text, never resolving to the actual stored procedure name.
2. How to Get the Current Stored Procedure's Name
If you need to reference the current procedure's name within the procedure itself (for execution, logging, or generating test commands), use the @@PROCID system function. It returns the object ID of the currently executing procedure, which you can combine with OBJECT_NAME() and OBJECT_SCHEMA_NAME() to get the full qualified name:
-- Retrieve full qualified stored procedure name SELECT OBJECT_SCHEMA_NAME(@@PROCID) + '.' + OBJECT_NAME(@@PROCID) AS CurrentStoredProcedure;
A Practical Workaround for Your Test Comment Needs
Since static comments can't handle dynamic replacement, here's a solution to avoid manual edits when copying test execution commands:
Add a small debug block in your stored procedure that dynamically generates the exact EXEC statement. Run this block to get a ready-to-use command you can copy anywhere:
-- Debug: Generate execution command (run this to get the EXEC line) DECLARE @TestExec NVARCHAR(MAX) = 'EXEC ' + OBJECT_SCHEMA_NAME(@@PROCID) + '.' + OBJECT_NAME(@@PROCID); PRINT @TestExec; -- Uncomment below to execute directly -- EXEC sp_executesql @TestExec;
Every time you copy this block to a new procedure, running it will output the correct EXEC [schema].[uspNameOfSP] line—no manual edits required.
If you use SQL Server Management Studio (SSMS), you can even turn this into a custom code snippet to insert the debug block with just a few keystrokes, making the process even faster.
内容的提问来源于stack exchange,提问作者user1734974

