SCOPE_IDENTITY() is returning NULL instead of expected value

799 Views Asked by At

With Python and SQL Server, I am inserting a row into table. Post record insertion, I am using SCOPE_IDENTITY() to get latest ID for inserted record. Instead of receiving expected ID, the function is returning NULL. Please can anyone help me getting latest ID for inserted record.

Python code:

InsertFileQuery = """
BEGIN
   BEGIN
    INSERT INTO [MYDB].[dbo].[TABLE]([A] ,[B],[C] ,[D] ,[E] ,[F])
                  VALUES (?,?,?,?,?,?,?)
   END
END
                 """

values = (A, B, C, D, E, F)
cursor = conn.cursor()
cursor.execute(InsertFileQuery, values)

cursor.execute("select SCOPE_IDENTITY()")
row = cursor.fetchone()
seed_id = row[0]
print(row)       #Null Value
print(seed_id)   #Null Value
1

There are 1 best solutions below

0
Greg Low On

Don't have anywhere to test it right now but it looks to me like this should work:

InsertFileQuery = """
    INSERT INTO [MYDB].[dbo].[TABLE]([A] ,[B],[C] ,[D] ,[E] ,[F])
                  VALUES (?,?,?,?,?,?,?);
    SELECT SCOPE_IDENTITY();
                 """

values = (A, B, C, D, E, F)
cursor = conn.cursor()
cursor.execute(InsertFileQuery, values)

row = cursor.fetchone()
seed_id = row[0]
print(row)       #Null Value
print(seed_id)   #Null Value