Compartir a través de


Create a Default Unique ID Value for a Field Sample

File: ...\Samples\Solution\Db\Newid.scx

This sample uses a stored procedure in a database to provide a default primary key value.

To create a default unique ID

  1. Add a separate table to the database that stores the next ID for each table in the database.

    The name of the table in the sample is Ids.dbf. It contains two fields: Table C(10), NextID I.

  2. In the stored procedures of the database, create a function that returns the next ID value from the ID table.

    The name of the function in the sample is NewID. The code for this function is included in this topic.

  3. Set the default value for the field to the function.

NewID Stored Procedure

FUNCTION NewID(tcAlias)
LOCAL lcAlias, lnID, lcOldReprocess, lnOldArea

  lnOldArea = SELECT()
  
  IF PARAMETERS() < 1
    lcAlias = UPPER(ALIAS())
  ELSE
    lcAlias = UPPER(tcAlias)
  ENDIF
        
  lcOldReprocess = SET('REPROCESS')

  * Lock until user presses Esc
  SET REPROCESS TO AUTOMATIC

  IF !USED("IDS")
    USE newid!ids IN 0
  ENDIF
  SELECT ids
      
  IF SEEK(lcAlias, "Ids", "table")
    IF RLOCK()
      lnID = ids.nextid
      REPLACE ids.nextid WITH ids.nextid + 1
      UNLOCK
    ENDIF
  ENDIF
    
  SELECT (lnOldArea)
  SET REPROCESS TO lcOldReprocess
  
  RETURN lnID
ENDFUNC

See Also

Tasks

Solution Samples

Reference

Visual FoxPro Foundation Classes A-Z

Other Resources

Databases Solution Samples