Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Grid question
Message
Information générale
Forum:
Visual FoxPro
Catégorie:
Gestionnaire d'écran & Écrans
Titre:
Divers
Thread ID:
00303412
Message ID:
00303547
Vues:
21
>function new_key
>parameters tbl_name, key_field
>private newkey
> select max(&key_field) from &tbl_name into array temp
>if _tally >0 && found records
> newkey = temp(1)+1
>else && empty table
> newkey = 1
>endif
>return newkey

Lorne,

Your code can fail and generate two identical PK vlaues for two different users. It is not a good idea to generate a new key value from the table that it is a key to. Here's an example of a NextPK function that is fully self contained;
FUNCTION NextPK
* Generates a new PK for a table
LPARAMETERS pcTable
* Shift the table name to uppercase
pcTable = UPPER(pcTable)

* Declare variables as local so they don't interfere with other routines
LOCAL lcAlias, lnNewPK
* Save the name of the curretn work area
lcAlias = ALIAS()

* Get an empty work area
SELECT 0
IF NOT FILE("SysKeys.dbf")
   * If the SysKeys tablke does not exist, create it
   CREATE FREE TABLE SysKeys ;
                    (TableName C(40), ;
                     LastID  I )
   INDEX ON UPPER(TableName) TAG TbaleName
ENDIF

IF USED("SysKeys")
   * If SysKeys is open select it
   SELECT SysKeys
ELSE
   * If it is not open, open it
   USE SysKeys
ENDIF
* Set the index order
SET ORDER TO TableName

* Find the record for the requested table
SEEK pcTable

IF NOT FOUND()
   * If the table was not foudn create a record for it
   INSERT INTO SysKeys (TableName, LastID) ;
                VALUES (pcTable, 1)
   lnNewPK = 1
ELSE
   * If the table was found increment the id under protection of a lock
   DO WHILE NOT RLOCK()
   ENDDO
   lnNewPK = SysKeys.LastID + 1
   REPLACE LastID WITH lnNewPK
   UNLOCK
ENDIF

* Restore the original work area
IF NOT EMPTY( lcAlias )
   SELECT ( lcAlias )
ELSE
   SELECT 0
ENDIF

* Return the new ID
RETURN lnNewPK
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform