I am using sqlalchemy
and python3
to query a database on Microsoft SQL Server
.
Since I do not have access to SQL Server Management Studio
I am resorting to using SHOWPLAN
options in my queries. I found this outlined in answer here:
How do I obtain a Query Execution Plan?
The problem is the output of using STATISTICS XML ON
is not human friendly. I generally use sqlalchemy
to retrieve data in pandas
dataframes so please forgive my ignorance if I am missing something obvious to interpret this in a friendlier manner.
Please find my python3 code below:
from sqlalchemy import create_engine
import os
database_credentials = config.settings['database_credentials']
# Retrieve database credentials from config
db_name = os.environ.get(database_credentials['db_name'])
db_host = os.environ.get(database_credentials['db_host'])
db_port = os.environ.get(database_credentials['db_port'])
db_id = os.environ.get(database_credentials['db_id'])
db_pwd = os.environ.get(database_credentials['db_pwd'])
# Concatenate strings to create database url
db_engine = create_engine('mssql+pymssql://' + db_id + ':' + db_pwd + '@' + db_host + ':' + db_port + '/' + db_name)
# Connect to database
db_conn = db_engine.connect()
# Example query with SHOW Plan options
query = 'SET STATISTICS XML ON\n SELECT TOP 5 * FROM Table'
# Execute the query
result = db_engine.execute(query)
Is there a way to format result
into something that is readable to understand the query plan?
Thanks for your help