denisenkom / pytds

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

lastrowid or alternative #113

Open bacchilu opened 4 years ago

bacchilu commented 4 years ago

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.

denisenkom commented 4 years ago

You can use @@identity or SCOPE_IDENTITY(): https://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/

allaboutmikey commented 3 years ago

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:

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