Author: Tomas Rutkauskas
Aside from using the Database Desktop to copy the structure of a Paradox table to a
new one, is there a way or a utility to reset a Paradox AutoInc to one (for any
empty table) or to the next number after the maximum value for the field?
Answer:
You would have to restructure the table and change the field type to long integer
then restructure the table and change the field type back to autoinc. An
alternative is to generate your own autoinc value. Create a single field single
record table to hold the last number used then use the following code to get the
next value.
1 2 function dgGetUniqueNumber(LastNumberTbl: TTable): LongInt;
3 {Gets the next value from a one field one record table which stores the last used 4 value in its first field. The parameter LastNumberTbl is the table that contains 5 the last used number.}6 const7 ntMaxTries = 100;
8 var9 I, WaitCount, Tries: Integer;
10 RecordLocked: Boolean;
11 ErrorMsg: string;
12 begin13 Result := 0;
14 Tries := 0;
15 with LastNumberTbl do16 begin17 {Make sure the table contains a record. If not, add one and set the first 18 field to zero.}19 if RecordCount = 0 then20 begin21 Insert;
22 Fields[0].AsInteger := 0;
23 Post;
24 end;
25 {Try to put the table that holds the last used number into edit mode. If 26 calling Edit raises an27 exception wait a random period and try again}28 Randomize;
29 while Tries < ntMaxTries do30 try31 Inc(Tries);
32 Edit;
33 Break;
34 except35 on E: EDBEngineError do36 {The call to Edit failed because the record could not be locked.}37 begin38 {See if the lock failed because the record is locked by another user}39 RecordLocked := False;
40 for I := 0 to Pred(E.ErrorCount) do41 if E: Errors[I].ErrorCode = 10241 then42 RecordLocked := True;
43 if RecordLocked then44 begin45 {Wait for a random period and try again}46 WaitCount := Random(20);
47 for I := 1 to WaitCount do48 Application.ProcessMessages;
49 Continue;
50 end51 else52 begin53 {The record lock failed for some reason other than another user has the 54 record locked.55 Display the BDE error stack and exit}56 ErrorMsg := '';
57 for I := 0 to Pred(E.ErrorCount) do58 ErrorMsg := ErrorMsg + E.Errors[I].message + ' (' +
59 IntToStr(E.Errors[I].ErrorCode) + '). ';
60 MessageDlg(ErrorMsg, mtError, [mbOK], 0);
61 Exit;
62 end;
63 end;
64 end;
65 if State = dsEdit then66 begin67 Result := Fields[0].AsInteger + 1;
68 Fields[0].AsInteger := Result;
69 Post;
70 end71 else72 {If the record could not be locked after the specified number of tries raise 73 an exception}74 raise Exception.Create('Cannot get next unique number. (dgGetUniqueNumber)');
75 end;
76 end;