In Microsoft SQL Server how can I get a query execution plan for a query / stored procedure?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
Query plans can be obtained from an Extended Events session via the
query_post_execution_showplan
event. Here's a sample XEvent session:After you create the session, (in SSMS) go to the Object Explorer and delve down into Management | Extended Events | Sessions. Right-click the "GetExecutionPlan" session and start it. Right-click it again and select "Watch Live Data".
Next, open a new query window and run one or more queries. Here's one for AdventureWorks:
After a moment or two, you should see some results in the "GetExecutionPlan: Live Data" tab. Click one of the query_post_execution_showplan events in the grid, and then click the "Query Plan" tab below the grid. It should look similar to this:
EDIT: The XEvent code and the screen shot were generated from SQL/SSMS 2012 w/ SP2. If you're using SQL 2008/R2, you might be able to tweak the script to make it run. But that version doesn't have a GUI, so you'd have to extract the showplan XML, save it as a *.sqlplan file and open it in SSMS. That's cumbersome. XEvents didn't exist in SQL 2005 or earlier. So, if you're not on SQL 2012 or later, I'd strongly suggest one of the other answers posted here.
Starting from SQL Server 2016+, Query Store feature was introduced to monitor performance. It provides insight into query plan choice and performance. It’s not a complete replacement of trace or extended events, but as it’s evolving from version to version, we might get a fully functional query store in future releases from SQL Server. The primary flow of Query Store
Enabling the Query Store: Query Store works at the database level on the server.
tempdb
database.Collect Information in the Query Store: We collect all the available information from the three stores using Query Store DMV (Data Management Views).
Query Plan Store: Persisting the execution plan information and it is accountable for capturing all information that is related to query compilation.
Runtime Stats Store: Persisting the execution statistics information and it is probably the most frequently updated store. These statistics represent query execution data.
Query Wait Stats Store: Persisting and capturing wait statistics information.
NOTE: Query Wait Stats Store is available only in SQL Server 2017+
Like with SQL Server Management Studio (already explained), it is also possible with Datagrip as explained here.