Search code examples
pythonpymssql

pymssql ( python module ) unable to use temporary tables


This isn't a question, so much as a pre-emptive answer. (I have gotten lots of help from this website & wanted to give back.)

I was struggling with a large bit of SQL query that was failing when I tried to run it via python using pymssql, but would run fine when directly through MS SQL. (E.g., in my case, I was using MS SQL Server Management Studio to run it outside of python.)

Then I finally discovered the problem: pymssql cannot handle temporary tables. At least not my version, which is still 1.0.1.

As proof, here is a snippet of my code, slightly altered to protect any IP issues:

conn = pymssql.connect(host=sqlServer, user=sqlID, password=sqlPwd, \
                       database=sqlDB)
cur = conn.cursor()
cur.execute(testQuery)

The above code FAILS (returns no data, to be specific, and spits the error "pymssql.OperationalError: No data available." if you call cur.fetchone() ) if I call it with testQuery defined as below:

testQuery = """
CREATE TABLE #TEST (
[sample_id] varchar (256)
,[blah] varchar (256) )
INSERT INTO #TEST
SELECT DISTINCT
        [sample_id]
        ,[blah]
FROM [myTableOI]
WHERE [Shipment Type] in ('test')

SELECT * FROM #TEST
"""

However, it works fine if testQuery is defined as below.

testQuery = """
SELECT DISTINCT
        [sample_id]
        ,[blah]
FROM [myTableOI]
WHERE [Shipment Type] in ('test')

"""

I did a Google search as well as a search within Stack Overflow, and couldn't find any information regarding the particular issue. I also looked under the pymssql documentation and FAQ, found at http://code.google.com/p/pymssql/wiki/FAQ, and did not see anything mentioning that temporary tables are not allowed. So I thought I'd add this "question".


Solution

  • Update: July 2016

    The previously-accepted answer is no longer valid. The second "will NOT work" example does indeed work with pymssql 2.1.1 under Python 2.7.11 (once conn.autocommit(1) is replaced with conn.autocommit(True) to avoid "TypeError: Cannot convert int to bool").