retrieve most recently executed SQL command (T-SQL) - sql

One of my developers working on a trigger-based logging facility in SQL Server 2008 asked me if there was a command to retrieve the most recently executed SQL command within T-SQL. I thought there was a system stored procedure for just such a function, but it's possible I'm thinking of another product from a prior decade... online searches yielded us no results.
Does anyone have information on anything of the sort?

sure try this :
SELECT
DMExQryStats.last_execution_time AS [Executed At],
DMExSQLTxt.text AS [Query]
FROM
sys.dm_exec_query_stats AS DMExQryStats
CROSS APPLY
sys.dm_exec_sql_text(DMExQryStats.sql_handle) AS DMExSQLTxt
ORDER BY
DMExQryStats.last_execution_time DESC
it will returns recently executed queries along with the date and time at which they were executed

Well, the procedure that retrieves the most current SQL batch can safely return itself :)
On a serious note, you can look at sys.dm_exec_query_stats and sys.dm_exec_procedure_stats to see when a plan was last time executed, based on the last_execution_time column. But note that the method is not reliable because it does not account for plans that were evicted from the cache after execution.

What does "most recent" mean in the context of a multi-core machine?
Also, does he mean the most recently started, or the most recently finished?
Finally, he should just open SSMS and look at Activity Monitor.

Related

Azure Get Live Queries

I'm looking for a query to get the current running queries in Azure SQL. All of the T-SQL I've found do not show the running queries when I test them (for instance, run a query in one window, then look in another window at the running queries). Also, I'm not looking for anything related to the time, CPU, etc, but only the actual running query text.
When I run ...
SELECT * FROM Table --(takes 2 minutes to load)
... and run a standard information query (like from Pinal Dave or this), I don't see the above query (I assume there's another way).
select * from sys.dm_exec_requests should give you what other sessions are doing.You can join this with sys.dm_exec_sql_text to get the text if needed. sys.dm_tran_locks gives the locks hold / waiting. If this is V12 server you can also use dbcc inutbuffer. Make sure that the connection you are running is dbo / server admin

How to determine which stored procedures are being executed (MSSQL 2008 R2)

I'm having a real problem with my application and SQL Server (2008 R2).
I have a bug whereby a stored procedure is failing because of a misconfigured SQLCMD variable but the call to the stored procedure is in an assembly for which I don't have the source code.
Is there a way to watch which stored procedures are being executed? Or is there a way to determine with an SQL query which stored procedures have been executed and when?
I am really stuck. Please help!
M
You could try running this against your database:
select OBJECT_NAME([object_id], database_id), last_execution_time, execution_count
from sys.dm_exec_procedure_stats
order by last_execution_time desc
Documentation: http://msdn.microsoft.com/en-us/library/cc280701.aspx
That gives you a snapshot at the time of execution what was last run and how many times it's been executed since it was last compiled. The table doesn't unfortunately give a log per-se of the stored procedures getting run, just when they were run last and some other helpful information.
Fore a much more involved approach, you could look at SQL Server Audit, a new feature to SQL Server 2008. I don't have much experience with it, but this should give you a starting point if you're super stuck.

View specific executed queries within SQL Server Management Studio?

Continuing from this post - I have some more questions I hope someone can help me with:
Is there a way to select a specific database and/or table to get the queries from or add this as a column?
In my queries there are some variables shown as #P1 or #GUID. Is there a way to get the data that was inserted there?
I am only using Express to I also have no access to SQL Profiler.
sys.dm_exec_sql_text has a dbid column, so you can filter on that. For example I took the query from the other answer and added a where clause filtering on queries against master:
SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('master')
ORDER BY deqs.last_execution_time DESC
Note that not all queries have the right database context (or a database context at all). For example, if you have a query that joins two tables that are in different databases, you will only see one dbid - it will either be the executing context and may or may not be one of the databases referenced in the query. So applying the filter might actually hide queries you are interested in.
You may be able to obtain parameters by digging into the XML from other DMOs such as sys.dm_exec_cached_plans and sys.dm_exec_query_plan. If you have an execution plan already for a query that you've captured, it is going to be much easier to use a tool like SQL Sentry Plan Explorer than to wade through gobs of XML yourself.
Disclaimer: I work for SQL Sentry, who provides the free tool to the community.
Just an FYI, you know that even though SQL Express doesn't include profile, if you have access to it you can use.

Measuring the Performance of SQL Queries

Let me say ahead of time, that I have very little understanding of the algorithms that SQL queries go through, so please excuse my ignorance.
My question is: How do you go about evaluating the performance of a particular SQL query? And what metrics are considered?
For example,
SELECT * FROM MyTable;
and
SELECT * FROM MyTable UNION SELECT * From MyTable;
I'm guessing the second one is a lot slower even though both queries return the same results. But, how could someone evaluate the two and decide which one is better and why?
Are there tools to do this? Is there any type of SQL stack trace? Etc...
Thanks.
Assuming you're talking about SQL Server (you didn't specify...):
You need to look into SQL Server Profiler - and the best intro around is a six-part webcast series called
Mastering SQL Server Profiler
in which Brad MacGehee walks you through how to start using Profiler and what to get from it.
Red-Gate Software also publishes a free e-book on Mastering SQL Server Profiler (also by Brad)
Also assuming you are talking about SQL Server, if you are using SQL Server Management Studio, then you can try 'Display Estimatesd Execution Plan' and/or 'Include Actual Execution Plan' (from the Query menu).
The difference is that the first one doesn't execute the query, while the second does. So the second is more accurate, but the first is useful if you only want to execute the 'lighter' query.
Both of them display the execution tree. You can hover over each node and see statistics.
The one to use to compare is 'Estimate Subtree Cost' (the higher the worse).
Hope this was helpful.

What is your FIRST SQL command to run to troubleshoot SQL Server performance?

When the SQL Server (2000/2005/2008) is running sluggish, what is the first command that you run to see where the problem is?
The purpose of this question is that, when all answers are compiled, other users can benefit by running your command of choice to segregate where the problem might be.
There are other troubleshooting posts regarding SQL Server performance but they can be useful only for specific cases.
If you roll out and run your own custom SQL script,
then would you let others know what
the purpose of the script is
it returns (return value)
to do to figure out where problem is
If you could provide source for the script, please post it.
In my case,
sp_lock
I run to figure out if there are any locks (purpose) to return SQL server lock information. Since result set displays object IDs (thus not so human readable), I would usually skim through result to see if there are abnormally many locks.
Feel free to update tags
Why run a single query when a picture is worth a thousand words!
I prefer to run the freely avaialable Performance Dashboard Reports.
They provide a complete snapshot overview of your servers performance in seconds. You can then choose the a specific area to investigate (locking, currently running queries, wait requests etc.) simply by clicking the apporpriate area on the Dashboard.
http://www.microsoft.com/downloads/details.aspx?FamilyId=1d3a4a0d-7e0c-4730-8204-e419218c1efc&displaylang=en
One slight caveat, I beleive these are only available in SQL 2005 and above.
sp_who
http://msdn.microsoft.com/en-us/library/aa260384(SQL.80).aspx
I want to see "who", what machines/users are running what queries, length of time, etc. I can also easily scan for blocks.
If something is blocking a bunch of other transactions I can use the spid to issue a kill command if necessary.
sp_who_3 - Provides a lot of information available elsewhere but in one nice output. Also has several parameters to allow customized output.
A custom query which combines what you would expect in sp_who with DBCC INPUTBUFFER(spid) to get the last query text on each spid ordered by the blocked/blocking graph.
Process data is avaliable via master..sysprocesses.
sp_who3 returns standand sp_who2 output, until you specify a specific spid, then gives 6 different recordsets about that spid including locks, blocks, what it's currently doing, the T/SQL it's running, and the statement within the T/SQL that is currently running.
Ian Stirk has a great script I like to use as detailed in this article: http://msdn2.microsoft.com/en-ca/magazine/cc135978.aspx
In particular, I like the missing indexes one:
SELECT
DatabaseName = DB_NAME(database_id)
,[Number Indexes Missing] = count(*)
FROM sys.dm_db_missing_index_details
GROUP BY DB_NAME(database_id)
ORDER BY 2 DESC;
DBCC OPENTRAN to see what the oldest active transaction is
Displays information about the oldest
active transaction and the oldest
distributed and nondistributed
replicated transactions, if any,
within the specified database. Results
are displayed only if there is an
active transaction or if the database
contains replication information. An
informational message is displayed if
there are no active transactions.
followed by sp_who2
I use queries like those:
Number of open/active connections in ms sql server 2005