Hacker’s Guide to Visual FoxPro
An irreverent look at how Visual FoxPro really works. Tells you the inside scoop on every command, function, property, event and method of Visual FoxPro.
SET KEY
, Set(“Key”)This command is a good alternative to setting a filter when you want to narrow down the visible records based on the current index. It lets you specify an index key or range of keys to be filtered in.
SET KEY TO [ uKeyValue ] [ IN cAlias | nWorkArea ]
SET KEY TO RANGE uLowKey, uHighKey
| RANGE uLowKey, | RANGE , uHighKey
[ IN cAlias | nWorkArea ]
cKeyValues = SET( "KEY" )
cLowKey = SET( "KEY", 1)
cHighKey = SET( "KEY", 2)
SET KEY
is similar to SET FILTER
, except that it uses the current index order. And except that, used with grids (where filters aren’t optimized), SET KEY
is much, much, much faster than the equivalent filter.
There are two flavors of SET KEY
. You can allow only records with a particular key value or you can limit it to a range of values. It turns out, though, that often there’s not a lot of difference because, with SET EXACT
OFF, you can specify partial key values, too. As with filters, you have to do something to move the record pointer to the first matching record.
The optional IN clause lets you SET KEY
in any work area, not just the current one. To turn off a character key filter in another work area, you can SET KEY
TO “” IN ThatArea, but we can’t figure out how to turn off other key filters remotely.
Changing the index order turns off the key filter, which makes sense since it’s based on the active index. If you need to temporarily change order, be sure to save and restore the KEY setting.
SET(“KEY”) lets you find out the current settings. With no second parameter, it returns the whole range. Pass either 1 or 2 to find out the lower or upper bound of the range. If you set only a single value (by omitting the RANGE keyword), the single value is used as both the lower and upper bound and is returned by both SET(“KEY”,1) and SET(“KEY”,2). However, if you use the RANGE keyword and omit either boundary, that version of the function returns a string of spaces.
VFP 7 Service Pack 1 fixes two bugs that were introduced in VFP 7. The first bug was that SEEK(), INDEXSEEK() and LOOKUP() would find records that were outside the scope of SET KEY. The second bug was pretty obscure: If the key length for the index used by SET KEY was exactly 240 characters, not all records that should have been in scope were. |
USE Customer
SET ORDER TO Company_Na
* limit to customers beginning with "G"
SET KEY TO "G"
? SET("KEY") && Returns "G, G"
? SET("KEY",1) && Returns "G"
? SET("KEY",2) && Returns "G"
* limit to customers between "Fo" and "Fu"
SET KEY TO RANGE "Fo","Fu"
? SET("KEY") && Returns "Fo, Fu"
? SET("KEY",1) && Returns "Fo"
? SET("KEY",2) && Returns "Fu"
* limit to customers up to "K"
SET KEY TO RANGE , "K"
? SET("KEY") && Returns ",K"
? SET("KEY",1) && Returns " "
? SET("KEY",2) && Returns "K"
* make all customers visible
SET KEY TO