denisenkom / pytds

Python DBAPI driver for MSSQL using pure Python TDS (Tabular Data Stream) protocol implementation

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

lastrowid or alternative

bacchilu opened this issue · comments

Is there a way to get the inserted ID after an INSERT? Something equivalent to the lastrowid field, that is not available in this library.

My favourite solution to this problem in postgres was to use the "returning" keyword.
I just discovered last week that TSQL has an "output" keyword that does basically the same thing.
From my recent code:

cur.execute("insert into SignedDocuments (DocumentName, DocType, EmpQualID, ScanData) "
                    "OUTPUT INSERTED.DocumentID "
                    "values (%(title)s,%(doctype)s,%(qualid)s,%(data)s)", params)
sdocid = cur.fetchone()['DocumentID']

You read the results back just like data returned from a normal select query.

The "output" keyword is a much more robust solution, IMHO, than the various "last generated id" calls you can make:

  • It doesn't require a second query and round trip to the database.
  • Explicit is better than Implicit, This is a much clearer, self documenting way to get an ID.
  • You can return multiple fields, including calculated fields, so you can have related info in the other fields of the row to help you identify which data the ID belongs to. This is particularly useful when you realise:
  • You can even return multiple rows for statements that affect more than one row.
  • You can use calculated output fields to return the difference/sum/whatever of the old and new values in a field for updates.
  • Using "output" is way cooler! :)

Find the manual entry at https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-ver15