Search code examples
sql-serverpython-3.xpymssql

How to create and recreate a index in Pymmsql in Python?


I'm trying to create and recreate indexes in Python but when I use this I get an error.

Error:
  File "src\pymssql.pyx", line 468, in pymssql.Cursor.execute
  pymssql.OperationalError: (7999, b"Could not find any index named 'Micros' for table 
  'payrolldata'.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages 
  from the SQL Server\n")

Code:

with pymssql.connect ("127.0.0.1","arcdbadmin", "@rcT3chn010g13$","Micros") as myDbConn:
   with myDbConn.cursor(as_dict=True) as cursor:
       cursor.execute("""create index Micros on payrolldata(stono,payrollid,busdate) WITH(DROP_EXISTING = ON);""")
       myDbConn.commit()
           

Solution

  • You can't use WITH(DROP_EXISTING = ON) unless the index already exists.

    You can drop index if exists first:

    drop index if exists Micros on payrolldata
    

    first if you want. On older versions you can run

    if exists (select * from sys.indexes where name = 'Micros' and object_id('payrolldata') = object_id)
    begin
      drop index micros on payrolldata
    end