c# - How to get the last number in a database column then increment it to include in another record? -


i have been given task of rewriting , old work application classic .asp asp.net includes database table not have auto incremented primary key. want continue use table maintain database integrity (it has 80,000+ records!). problem running need able pull last item id column of database table regardless of how old record is, increment number , include in new record inserted new record's id number. how go doing this? have tried listitem, datareader, datatables, generic lists (as objects), , arraylists. can pull information , store it, cannot last item in collection itself. suggestions appreciated.

 protected void getprimarykey()  {      string strsql = "";       try      {           oledbconnection dbconn = new oledbconnection();           dbconn.connectionstring = system.web.configuration.webconfigurationmanager.connectionstring["connectionstring"].tostring();            strsql = "select observationid observation";           oledbcommand mycmd = new oledbcommand(strsql, dbconn);           oledbreader reader;            listitem item;            if (dbconn.state == connectionstate.colsed) dbconn.open();           reader = mycmd.executereader();           while (reader.read())           {                item = new listitem();                item.text = reader["observationid"].tostring();           }           reader.close();           dbconn.close();           mycmd.dispose();       }  } 

populating list code at. last item still needs found incremented, , returned submit button event handler starts whole process. know code missing lot, didn't want send entire commented mess. again, appreciated. thank you.

select top 1 observationid observarion order observationid desc  

this return last row id

if more 1 person try value insert, run issue end same ids, unless column unique , throw error.

to minimize issues, can inline select in insert statement.

insert observation (observationid) values(select top 1 (observationid + 1) newobservationid observation order observationid desc) 

not sure if syntax correct should lead in right direction.


Popular posts from this blog