使用 INSERT ... OUTPUT 和 pyodbc 时如何获取 IDENTITY 值

How to get the IDENTITY value when using INSERT ... OUTPUT with pyodbc

我正在尝试使用 OUTPUT 获取新插入行的 ID。但是,我遇到了HY010错误。下面的query/code是我用的:

string = """
         SET NOCOUNT ON;
         DECLARE @NEWID TABLE(ID INT);

         INSERT INTO dbo.t1 (Username, Age)
         OUTPUT inserted.id INTO @NEWID(ID)
         VALUES(?, ?)

         SELECT ID FROM @NEWID
         """

cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]

最后一行 id = cursor.fetchone()[0] 导致了 HY010 错误(见下文)。任何建议将不胜感激!

pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC SQL Server Driver]Function sequence error (0) (SQLFetch)')

我能够重现您的问题,并且能够通过在 INSERT 之后立即检索 id 值并在提交 之前 来避免它。也就是说,而不是

cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]

我做到了

cursor.execute(string, "John Doe", 35)
id = cursor.fetchone()[0]  # although cursor.fetchval() would be preferred
cursor.commit()

如果您将 SQLAlchemy 与 engine 一起使用,那么您可以在 运行 查询和获取 table ID 之前像这样检索 PyODBC 游标。

    connection = sql_alchemy_engine.raw_connection()
    cursor = connection.cursor()
    result = cursor.execute(
        """
        INSERT INTO MySchema.MyTable (Col1, Col2) OUTPUT INSERTED.MyTableId 
        VALUES (?, ?);
        """,
        col1_value,
        col2_value,
    )
    myTableId = cursor.fetchone()[0]
    cursor.commit()
    print("my ID is:", myTableId)

对我来说,只有这适用于 Azure SQL 无服务器(使用 pyodbc==4.0.28):

cursor.execute(insert_statement, param_value_list)
cursor.execute("SELECT @@IDENTITY AS ID;")
return cursor.fetchone()[0]