如何在SQL中获取最后创建的ID

vcv*_*cvd 8 python sql sql-server pyodbc

我创建了一个名为participant的表,该表由participant_ID(它是主键并且是identity [具有自动值])和session_ID(它是外键)组成.

当我创建一个新参与者时,我想存储其participant_ID.

我有以下代码,但我收到以下消息错误:'返回附近的语法问题'

connection = pyodbc.connect('Driver={SQL Server Native Client 11.0};Serve=:xxx;Database=xxx;Uid=xxx;Pwd=xxx')
cur = connection.cursor()
pID = cur.execute('INSERT INTO participant(sessions_ID) VALUES (40) RETURNING participant_ID')
Run Code Online (Sandbox Code Playgroud)

提前谢谢了!

Ste*_*veJ 9

这是一个非常非常古老的帖子,我知道 - 但我有同样的问题并且发现了它.我得到了我的工作,并认为我会分享那些在我身边跌跌撞撞的人.请善待,这是我在代码中的第一次传递.它不漂亮,但它应该让你开始.

def exec_query(self, query_type, query):
    # query_type: This is an enumumeration defining the CRUD operation of the query.

    # Note, the native client (11.0) might change with time and Windows updates)
    # Note, the driver varlue would normally go in a constant, I put it here just for clarity
    with pypyodbc.connect('DRIVER={SQL Server Native Client 11.0}; ' + self.cnx_str) as connection:
        cursor = connection.cursor()
        cursor.execute(query)

        if query_type is QueryType.create:
            try:
                cursor.execute("SELECT SCOPE_IDENTITY()")
                row = cursor.fetchone()
                seed_id = row[0]
            except AttributeError:
                seed_id = 0
            cursor.commit()
            return seed_id

        # ... Additional code for non 'create' operations
Run Code Online (Sandbox Code Playgroud)


Szy*_*mon 8

你可以用两种方式做到这一点

  1. select SCOPE_IDENTITY() - 这是首选,因为它受到您创建的身份的范围的限制.

  2. select @@IDENTITY - 这是无论范围如何都创建的最后一个标识(例如,触发器可以创建其他标识).

点击此处查看更多信息:http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/


小智 0

请在插入查询后尝试,SELECT @@Identity这将返回当前连接的主键标识列值。