Question

I'm trying to execute TSQL queries in a remote MSSQL database by using SQLAlchemy and pymssql. I've tested my procedural query directly in the database and it works as intended, it also works if I run it directly through pymssql. If I run a regular one liner queries such as:

select table_name from INFORMATION_SCHEMA.tables

Through SQLAlchemy this also works as it should. But when I try to execute the following TSQL query it does not actually create the table:

IF NOT EXISTS (SELECT * 
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME = 'SOME_TABLE')
BEGIN
   CREATE TABLE SOME_TABLE (SOME_TEXT VARCHAR(255), SOME_TIME DATETIME)
END

it runs it as it was successful and if I try to read the result it from the execution it gives me "Resource already closed error" as expected since it is a CREATE query. However if I try to add data to table 'SOME_TABLE' it pukes at me and says that the table does not exist. Feels like it is only uploading the query as a function but never executes it. Any ideas? Or even better; TSQL queries that actually works when executing with SQLAlchemy and pymssql.

Thanks,

Était-ce utile?

La solution

You need to commit your pending changes in the Session. For basic understanding of the process read Using the Session. Quick solution:

session.commit()

Autres conseils

TIME and TEXT are reserve words.

I do not know how SQL Alchemy or pymmsql talks to SQL Server. Either native client or ODBC. It eventually all boils down to a tabular data stream (TDS) over a network protocol like TCP/IP.

Check out the reserve word list on TECHNET.

-- Create table ?
IF OBJECT_ID('DBO.SOMETABLE') IS NULL 
  CREATE TABLE DBO.SOMETABLE (MY_TEXT VARCHAR(255), MY_TIME DATETIME);

I use the OBJECT_ID function since it is less typing.

But NOT EXITS works with both SELECT FROM the sys.objects or information_schema.tables with correct WHERE clauses.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top