Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL. Text of procedure call

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?

like image 280
Eugene Avatar asked Dec 04 '12 13:12

Eugene


People also ask

How do I view stored procedure text in SQL?

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.

Can SQL view call stored procedure?

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.

Can procedure return a value?

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.

Can procedure be call in select statement?

You cannot call a procedure in a select statement, because it does not return anything.


1 Answers

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.

like image 65
András Ottó Avatar answered Sep 17 '22 15:09

András Ottó