denisenkom / pytds

Python DBAPI driver for MSSQL using pure Python TDS (Tabular Data Stream) protocol implementation
MIT License
191 stars 53 forks source link

Error getting results from TSQL statement #60

Closed obeleh closed 6 years ago

obeleh commented 8 years ago

query:

DECLARE @TOTAL_PLAN_CACHE BIGINT, @SINGLE_USE_PLAN_CACHE BIGINT;
SELECT @TOTAL_PLAN_CACHE = SUM(CAST(cp_tot.size_in_bytes AS BIGINT)) FROM sys.dm_exec_cached_plans AS cp_tot WHERE cp_tot.cacheobjtype = N'Compiled Plan';
SELECT @SINGLE_USE_PLAN_CACHE = SUM(CAST(cp_single.size_in_bytes AS BIGINT)) FROM sys.dm_exec_cached_plans AS cp_single
WHERE
    cp_single.cacheobjtype = N'Compiled Plan'
    AND cp_single.objtype IN (N'Adhoc', N'Prepared')
    AND cp_single.usecounts = 1;
SELECT @TOTAL_PLAN_CACHE AS total_plan_cache, @SINGLE_USE_PLAN_CACHE AS single_use_plan_cache, CAST(@SINGLE_USE_PLAN_CACHE AS float) / CAST(@TOTAL_PLAN_CACHE AS float) AS plan_bloat
import pytds
with pytds.connect('server', 'database', 'user', 'password') as conn:
    with conn.cursor() as cur:
        cur.execute(query)
        cur.fetchall()

Results in Previous statement didn't produce any results

However in SSMS (values are different because it's a different server) I get a result: image

And with the following hack I can get the results I'm looking for:

try:
    tmp = cur.return_value
except Exception:
    pass
print(cur._session.row)

[u'system', 4987691008, 2605195264, 0.5223249114312416]

dirkjonker commented 7 years ago

@obeleh you are not getting results because you have a query that contains multiple statements, and the first statement apparently does not return any rows. Call cur.nextset() until you arrive at the result set you are looking for. This is normal behavior. See also: https://github.com/denisenkom/pytds/blob/master/pytds/__init__.py#L701