Criando métodos e funções para agilizar o código - III

 

Veremos nessa dica, como criar um campo auto-incremento, utilizando o dbExpress. Primeiramente cria o seguinte procedimento:

 

procedure Incrementa(TableName: string ;

  PrimaryKey: TField; Connection : TSQLConnection);

 

E implemente-o com o seguinte código:

 

var

  Qry:TSQLQuery;

begin

{: cria uma autonumeração}

if PrimaryKey.DataSet.State <> dsInsert then

  Exit;

Qry := TSQLQuery.Create( nil );

  try

    {: componente de conexão }

    Qry.SQLConnection := Connection;

    Qry.SQL.Add('SELECT MAX('+PrimaryKey.FieldName+')FROM '+ TableName);

    Qry.Open;

    {: se a tabela está vazia, retornará nulo}

    if Qry.Fields[0].IsNull then

    {: então será o primeiro registro}

      PrimaryKey.AsInteger := 1

    else

      PrimaryKey.AsInteger := Qry.Fields[0].AsInteger+1;

  finally

    FreeAndNil(Qry);

  end ;

 

Após, basta “chamar” a procedure anterior, no evento BeforePost ou OnNewRecord do componente ( DataSet ) que esteja utilizando.

 

por Luciano Pimenta

webeditor@clubedelphi.net