You do not mention which SQL database you are using, but this is what I use with Microsoft SQL Server. I have a stored procedure I call that creates a new Orders record:
CREATE PROCEDURE CF0010_NewOrder
AS
set nocount on;
declare @MaxOrder Integer;
select @MaxOrder = IsNull(Max(OrderNum),11000
from orders;
set @MaxOrder = @MaxOrder + 1;
Insert
Into Orders (OrderNum, SubOrderNum)
VALUES (@MaxOrder, 0) ;
select OrderNum = @MaxOrder ;
set nocount off;
The key to this is that the OrderNum and SubOrderNum are the key fields for the Orders table. This procedure insures that the table is initialized if starting from scratch, inserts the new next-order into the table and then returns the OrderNum as an integer to the calling procedure. No transaction processing is done at the stored procedure level as I handle all of that in Delphi code myself.
I call this stored procedure like this:
var
rs_tmp : TADODataset;
...
with RS_Tmp do
begin
Close;
// connection info is stored in the properties on the TAdoDataset but could be defined here
//connection := ...
CommandType := cmdStoredProc;
CommandText := 'CF0010_NewOrder;1';
Active := True;
OrderNum := (RS_Tmp.FieldByName('Order
Close;
end;
The new OrderNum is returned and then you can prepend your "OTY/" to the returned integer for whatever you need it to do.
John
Main Topics
Browse All Topics





by: mikelittlewoodPosted on 2007-02-14 at 11:00:42ID: 18534181
I personally would use another table to hold next ID's then use this during your insert.
t(DataSet: TDataSet);
Below isn't exactly what I would do for real but gives you an idea of the general steps I would use.
Firstly I would have another function to get the next ID's from using another query.
I would then use this to populate the auto fields you want on an after insert of the ADO table.
The only thing I wasn't sure of is if you are upating the same table for both values.
procedure TForm1.ADOTable1AfterInser
var
iNextID: Integer;
sNextID: string;
begin
iNextID := GetNextID;
ADOTable1.FieldByName( 'PrimaryField').AsInteger := iNextID;
sNextID := IntToStr( iNextID);
// pad out the customer ref based on length of the next index
ADOTable1.FieldByName( 'customerref').AsString :=
'OTY/' + StringOfChar( '0', 4 - Length( sNextID)) + sNextID;
end;
function TForm1.GetNextID: integer;
begin
with ADOQuery1 do
begin
SQL.Text := 'SELECT NextID FROM KeyFile WHERE KeyTable = ' + QuotedStr( 'Customer');
Open;
Result := FieldByName( 'NextID').AsInteger;
end
end;