I'm trying to implement a generic logging for my stored procedures. The best solution I found is to use DBCC INPUTBUFFER, it returns the text of procedure call like:
DECLARE @a INT
SET @a = 1000
EXEC usp_Test @param = @a
But it has one limitation, the max length of this buffer is 4000. I have a lot of procedures that have table valued parameters and often they contain > 10000 records, so I can't log this call with this approach.
Is there any way to implement such logging without manual creating of 'Text of procedure call' in each procedure?
Using SQL Server Management StudioExpand Stored Procedures, right-click the procedure and then select Script Stored Procedure as, and then select one of the following: Create To, Alter To, or Drop and Create To. Select New Query Editor Window. This will display the procedure definition.
Answers. No, but most-likely you can convert your stored procedure to a table-valued function. Then you can call the table-valued function in a view.
A stored procedure does not have a return value but can optionally take input, output, or input-output parameters. A stored procedure can return output through any output or input-output parameter.
You cannot call a procedure in a select statement, because it does not return anything.
Instead of using DBCC INPUTBUFFER @SPID
, you can try to use the dm_exec_sql_text
It has a nvarchar(max)
field as Text
of the last SP.
Try to build a function for this code (expect the @SPID
as int parameter):
--Select the sql_handle first for the given session ID
DECLARE @sqltext VARBINARY(128)
SELECT @sqltext = sql_handle
FROM sys.sysprocesses
WHERE spid = @SPID
--Select the last statement
SELECT TEXT
FROM sys.dm_exec_sql_text(@sqltext)
An other way to use:
EXEC yourProcedure withYourParams
SELECT @sqltext = sql_handle FROM sys.sysprocesses WHERE spid = @@SPID
SELECT TEXT FROM ::fn_get_sql(@sqltext)
Instead of @SPID
parameter for this, you can use the @@SPID
, but then this code segment will be integrated with your last SP call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With