generating log timestamps using Stored procedures in SQL server 2005 - sql-server-2005

I have a Stored Procedure, Which has some select Statements and insert statements.
Is there any way , I can log the Timestamps of execution before and after the sqls inside the Stored procedure?

If this is not something you want to leave in permanently (i.e. it's just for debugging/performance analysis purposes) then your best bet is to use SQL Profiler and monitor the SP:StmtCompleted event which will record the stats for each statement within a sproc. You can dump this data to a db table.
Edit: Running SQL Profiler:
1) In SSMS, under Tools, select SQL Server Profiler
2) Connect to your db server you want to monitor
3) In the trace properties dialog that appears, go to the Events Selection tab and tick the "Show all events" checkbox
4) The grid will then show all types of events you can monitor. Find the Stored Procedures section, and in there cick the SP:StmtCompleted checkbox to define that you want to monitor that type of event.
5) The general tab allows you to save the trace to a file, or to a db table if you want to. Or, you don't have to save it to either, just display it to screen. You can always save it to a table/file later if you really need to.
6) When you're ready just click "Run"
For a lot more info on SQL Profiler, see MSDN
If this is something you want to keep (i.e. an audit table), then you'll need to INSERT records into your own audit table yourself e.g.
DECLARE #StartTime DATETIME
SET #StartTime = GETDATE()
SELECT Something FROM SomeTable WHERE....
INSERT MyAuditTable (Statement, StartTime, EndTime)
VALUES ('SELECT Something FROM SomeTable WHERE...', #StartTime, GETDATE())

Sure. Add TSQL to write to an audit table at the start and end of execution, adding TRY/CATCH error handling to make sure an early exit doesn't occur.

Related

Access to a session in SQL Server

I have a session created in my vb.net codes and running some SQL queries, there are some local temp tables like #T1, #T2 , ...
Execution process has some steps and I need to know which data changes in my local tables in each step.
Currently I use this to view the data in my code:
select * into ##T1 from #T1
I can't use sp_getbindtoken because there is no active transaction. I can not use DBCC because I don't have permission.
I can run sys.dm_exec_sessions view and therefor I have active session_id,
I also have connection Index of active sql connection
is there any way to connect to a active session and access local temp tables?
or is there any way to get those data of #T1, #T2,...?
EDIT1:
according to the comment which commented by #SeanLange
I have some temp tables as I said, and in the steps mentioned before I do some calculations on these temp tables, for tracing these calculations I need to know what happens in these steps, and I want to execute a simple select statement on these temp tables. what I wanted to do was connect to the active session created in my source code from an external project called Tracer, and perform select statements while my source is on the fly and meanwhile trace the data created in these session
You can't do it. Sorry. (at least without sa privileges).
Run your queries from within a stored procedure and add code to log whatever you need to a table, then query the log table as needed.
Execution process has some steps and I need to know which data changes in my local tables in each step.
If you have permission, you can create a trigger to do the logging for you

Count number of rows edited by Stored Proc

We have a stored procedure in a MSSQL Server 2008 database that performs a number of reads and writes in response to user action on a website.
I would like to know if there is any way of counting how many rows were edited/created during the procedure, preferably without having to alter the proc (although alterations are possible).
Does anyone have any suggestions? I looked at ##ROWCOUNT but that covers reads and writes (and I'd prefer not o go throught the proc and manually add up ROWCOUNT after each UPDATE)
EDIT: the proc is being called from C# using the System.Data.SqlClient classes
Without editing the proc, your best bet would be to start a SQL Server Profiler session, track SP:StmtCompleted, filter ObjectName to your proc, and filter TextData to the statements you want to monitor. Be sure to include the RowCount column.
Note that you can't get the row counts from the extended events sql_statement_completed event. There is no row count column; just duration, CPU, reads and writes.
If you can edit the proc, you would have total control over the behavior. You could sum up the ##ROWCOUNT of every INSERT/UPDATE/DELETE operation. This count could be returned as an output parameter, written to the log, PRINTed, traced with user-defined trace events, saved to a table, etc.
MS Sql Profiler is where you want to start for something like this.
##ROWCOUNT will give you counts based on the last run statement, so with that you could create a local variable and update it after everytime with ##ROWCOUNT
Otherwise you will have to get into Profiler and watch from there, but that is not a sustainable solution, better suited for troubleshooting.
I Have no idea about MySQL, But Oracle SQL provides a variable called SQL%ROWCOUNT, which contains the number of rows effected in the immediately previous transaction

SQL Server Profiler 2005: How to measure execution time of insert statement with trigger?

I want to measure the execution time (using I guess duration from SQL Server Profiler) of an insert statement that has an instead-of insert trigger on it. How do I measure the complete time of this statement including the trigger time?
The execution time (duration) that you see in SQL server profiler for a query is the time it took to execute that query including evaluating any triggers or other constraints.
Because triggers are intended to be used as an alternative way to check data integrity, an SQL statement is not considered to have completed until any triggers have also finished.
Update: An overview of some commonly used SQL Server profiler events:
SQL:BatchCompleted Occurs when a SQL server batch (a group of statements) has completed execution - the duration is the total time to execute the batch.
SQL:StmtCompleted Occurs when a SQL statement executed as part of a batch completes execution - again the duration is the time to execute that single statement.
SP:Completed Occurs when a stored procedure has completed execution - the duration shown is the time to complete execution of the stored procedure.
SP:StmtCompleted Occurs when an SQL statement executed as part of a stored procedure completes.
A batch is a set of SQL statements separated by a GO statement, however to understand the above you should also know that all SQL server commands are executed in the context of a batch*.
Also, each of the above events also has a corresponding Starting event - SP:Starting, SQL:BatchStarting, SQL:StmtStarting and SP:StmtCompleted. These don't list durations (as we don't know the duration yet because its not completed, however do help show when the duration recording starts from).
To better understand the relationship between these events, I recommend that you experiment with capturing some traces of some simple examples (from within SQL Server Management Studio), for example:
SELECT * FROM SomeTable
GO
SELECT * FROM SomeTable
SELECT * FROM OtherTable
GO
SELECT * FROM SomeTable
exec SomeProc
GO
As you should see, for each of the 3 examples above you always get a SQL:BatchStarting and SQL:BatchCompleted, the other event types however provide more detail on the individual commands run.
For this reason I generally tend to use the SQL:BatchCompleted event the most, however if the statement you are attempting to measure is executed as part of a larger batch (or in a stored procedure) then you may find one of the other event classes helpful.
See TSQL Event Category (MSDN) for more information on the various SQL Server Profiling events - there are lots!
Finally, if you are executing this command from within SQL Server Management studio, be aware that the simplest way to record the execution time is to use the client side statistics feature:
(*) I'm pretty sure that everything is executed as part of a batch, although I've not managed to find any evidence on the internet to confirm this.

How to troubleshoot a stored procedure?

what is the best way of troubleshoot a stored procedure in SQL Server, i mean from where do you start etc..?
Test each SELECT statements (if any) outside of your stored procedure to see whether it returns the expected results;
Make INSERT and UPDATE statements as simple as possible;
Try to test Inserts and Updates outside of your SP so that you can check it gives the expected results;
Use the debugger provided with SSMS Express 2008.
Visual Studio 2008 / 2010 has a debug facility. Simply connect to to your SQL Server instance in 'Server Explorer' and browse to your stored procedure.
Visual Studio 'Test Edition' also can generate Unit Tests around your stored procedures.
Troubleshooting a complex stored proc is far more than just determining if you can get it to run or not and finding the step which won't run. What is most critical is whether it actually returns the corect results or performs the correct actions.
There are two kinds of stored procs that need extensive abilites to troublshoot. First the the proc which creates dynamic SQL. I never create one of these without an input parameter of #debug. When this parameter is set, I have the proc print the SQl statment as it would have run and not run it. Almost everytime, this leads you right away to the problem as you can then see the syntax error in the generated SQL code. You also can run this sql code to see if it is returning the records you expect.
Now with complex procs that have many steps that affect data, I always use an #test input parameter. There are two things I do with the #test parameter, first I make it rollback the actions so that a mistake in development won't mess up the data. Second, I have it display the data before it rollsback to see what the results would have been. (These actually appear in the reverse order in the proc; I just think of them in this order.)
Now I can see what would have gone into the table or been deleted from the tables without affecting the data permananently. Sometimes, I might start with a select of the data as it was before any actions and then compare it to a select run afterwards.
Finally, I often want to log actions of a complex proc and see exactly what steps happened. I don't want those logs to get rolled back if the proc hits an error, so I set up a table variable for the logging information I want at the start of the proc. After each step (or after an error depending on what I want to log), I insert to this table variable. After the rollback or commit statement, I select the results of the table variable or use those results to log to a permanent logging table. This can be especially nice if you are using dynamic SQL because you can log the SQL that was run and then when something strange fails on prod, you have a record of which statement was run when it failed. You do this in a table variable because those do not go out of scope in a rollback.
In SSMS, you can simply start by opening the proc., and clicking on the check mark button (Parse) next to the Execute button on the menu bar. It reports any errors it finds.
If there are no errors there and you're stored procedure is harmless to run (you're not inserting into tables, just creating a temp table for example), then comment out the CREATE PROCEDURE x (or ALTER PROCEDURE x) and declare all the parameters by copying that part, then define them with valid values. Then run it to see what happens.
Maybe this is simple, but it's a place to start.

How to see the values of a table variable at debug time in T-SQL?

Can we see the values (rows and cells) in a table valued variable in SQL Server Management Studio (SSMS) during debug time? If yes, how?
DECLARE #v XML = (SELECT * FROM <tablename> FOR XML AUTO)
Insert the above statement at the point where you want to view the table's contents. The table's contents will be rendered as XML in the locals window, or you can add #v to the watches window.
That's not yet implemented according this Microsoft Connect link:
Microsoft Connect
This project https://github.com/FilipDeVos/sp_select has a stored procedure sp_select which allows for selecting from a temp table.
Usage:
exec sp_select 'tempDb..#myTempTable'
While debugging a stored procedure you can open a new tab and run this command to see the contents of the temp table.
In the Stored Procedure create a global temporary table ##temptable and write an insert query within your stored procedure which inserts the data in your table into this temporary table.
Once this is done you can check the content of the temporary table by opening a new query window.
Just use "select * from ##temptable"
If you are using SQL Server 2016 or newer, you can also select it as JSON result and display it in JSON Visualizer, it's much easier to read it than in XML and allows you to filter results.
DECLARE #v nvarchar(max) = (SELECT * FROM Suppliers FOR JSON AUTO)
I have come to the conclusion that this is not possible without any plugins.
SQL Server Profiler 2014 lists the content of table value parameter. Might work in previous versions too.
Enable SP:Starting or RPC:Completed event in Stored Procedures group and TextData column and when you click on entry in log you'll have the insert statements for table variable.
You can then copy the text and run in Management Studio.
Sample output:
declare #p1 dbo.TableType
insert into #p1 values(N'A',N'B')
insert into #p1 values(N'C',N'D')
exec uspWhatever #PARAM=#p1
Why not just select the Table and view the variable that way?
SELECT * FROM #d
Sorry guys, I'm a little late to the party but for anyone that stumbles across this question at a later date, I've found the easiest way to do this in a stored procedure is to:
Create a new query with any procedure parameters declared and initialised at the top.
Paste in the body of your procedure.
Add a good old fashioned select query immediately after your table variable is initialised with data.
If 3. is not the last statement in the procedure, set a breakpoint on the same line, start debugging and continue straight to your breakpoint.
Profit!!
messi19's answer should be the accepted one IMHO, since it is simpler than mine and does the job most of the time, but if you're like me and have a table variable inside a loop that you want to inspect, this does the job nicely without too much effort or external SSMS plugins.