Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to get the query plan out using jdbc on sql server?

I am using the JTDS driver and I'd like to make sure my java client is receiving the same query plan as when I execute the SQL in Mgmt studio, is there a way to get the query plan (ideally in xml format)?

basically, I'd like the same format output as

set showplan_xml on 

in management studio. Any ideas?

Some code for getting the plan for a session_id

SELECT usecounts, cacheobjtype,
  objtype, [text], query_plan
FROM sys.dm_exec_requests req, sys.dm_exec_cached_plans P
  CROSS APPLY
    sys.dm_exec_sql_text(plan_handle)
  CROSS APPLY
    sys.dm_exec_query_plan(plan_handle)    
WHERE cacheobjtype = 'Compiled Plan'
    AND [text] NOT LIKE '%sys.dm_%'
    --and text like '%sp%reassign%'
    and p.plan_handle = req.plan_handle
    and req.session_id = 70 /** <-- your sesssion_id here **/
like image 450
James B Avatar asked Nov 24 '09 17:11

James B


People also ask

How do you see query execution plan?

Shortcut key: There is a shortcut key available to check for the Estimated Execution plan. You can press Ctrl+L after writing the query in the Query window. In the Context Menu of the Query Window, you will find a menu on the toolbar in SQL Server Management Studio with the name “Display Estimated Execution Plan”.

What command is used to obtain the query execution plan?

Using the SHOWPLAN command Besides the graphical query plans, we can obtain the execution plans in text or XML format with help of the SET SHOWPLAN command.


1 Answers

  1. Identify your Java session id. Print @@SPID from java or use SSMS and look into sys.dm_exec_sessions and/or sys.dm_exec_connections for your Java client session (it can be identified by program_name, host_process_id, client_net_address etc).
  2. Execute your statement. Look in sys.dm_exec_requests for the session_id found at 1.
  3. Extract the plan using sys.dm_exec_query_plan from the plan_handle found at 2.
  4. Save the plan as a .sqlplan file and open it in SSMS

Alternatively you can use the Profiler, attach the profiler to server and capture the Showplan XML event.

like image 156
Remus Rusanu Avatar answered Sep 27 '22 20:09

Remus Rusanu