|
There's always the need to generate a Primary Key (PK) or a new
invoice number or any kind of unique number or code, without repetition.
There are, as always, different forms of accomplishing this. here's
a couple of them.
One way is to create a function, call it NewId() and use it as
the default for new records. This way, when creating or inserting
a new record, it will always be generated corrrectly and automatically.
Let's see how this works:
First, we must create a supporting table with the following structure:
TableName C(10)
LastID I
The LastID field will keep the last generated number or code for
each table. Ig you want to use alphanumercis instead, just change
its tyoe to C(5) or similar and then do a type conversion to add
one each time.
To look for the last number used by the name of our table create
an uppercase index:
INDEX ON UPPER(TableName) TAG TableName
Then, each time you need a new number, do a SEEK for the ALIAS()
of the table where you need to insert this ID. If you find it, do
a record llock and add 1 to itsaving and returning that number.
If not found, it means it is a new table, just add the record for
this table and start it at 1.
Example:
| TableName |
LastID |
| CLIENTS |
125 |
| INVOICES |
10 |
This way you will always have new, consecutive, non-repeating numbers.
Another way is by the use of a Globally Unique Identifier (GUID).
This is a 128-bit code that is guaranteed to be unique. This is
what is used in Windows for Registry keys and IDs.
If you have installed WSH 5.6 try the following, else you can download
it from Microsoft for free from
here. 
* In VFP 7
oGUID = CreateObject("scriptlet.typelib")
cGUID = Strextract(oGUID.GUID, "{", "}" )
* Previous VFP versions:
oGUID = CreateObject("scriptlet.typelib")
cGUID = substr( oGUID.GUID, 2, 36 )
(Thanks to David Frankenbach and Sergey
Berezniker for this sample).
|