3
  • ?"ABC">"A" returns .F.
  • ?"ABC">"B" returns .F.
  • ?"ABC">"a" returns .T.

This seems not an ASCII comparison (as in other common programming languages).

I'v searched MSDN, however Relational Operators only explained comparison across numeric type or boolean. String and Value Comparison didn't mention lt/gt/lte/gte operators.

Why string comparison work like this? What's VFP's internal rules for string lt/gt comparison?

Jamesits
  • 612
  • 7
  • 18

1 Answers1

6

Actually VFP's string comparison is not much different than in other languages (some languages -ie: C#- doesn't even let you use >=, >, <= and < with strings). However, in VFP there is one setting that affects string comparison and it is 'SET EXACT'. Other than that, VFP strings are case sensitive, thus "ABC" > "a" is false (alpha sort is based on their ASCII character codes).

With default SET EXACT OFF, strings are compared up to the length of right operand. ie: "ABC" = "A"

is compared like: "A" = "A"

thus they are equal, so "ABC" > "A" is false (and also "ABC" < "A" is false, "ABC" = "A" is true).

To recap, with default SET EXACT setting, which is OFF: "ABC" = "A" (but "A" = "ABC" is false - compare up to right operand's length).

AND, the alphabetic ordering use ASCII code.

SET EXACT OFF && Default if not set explicitly
? "ABC" = "A" && .T.
? "ABC" > "A" && .F.
? "ABC" < "B" && .T.

SET EXACT ON
? "ABC" = "A" && .F.
? "ABC" > "A" && .T.
? "ABC" < "B" && .T.

A special note: If you are doing this equality check in SQL commands, then there the ANSI rules are applied and SET EXACT has no effect there. By default SET ANSI is OFF and "ABC" = "A" (and due to SQL rules, changing the operands' left and right sides wouldn't matter, thus "A" = "ABC" is also true). ie:

Select * from myTable where firstName = "A"

would return records having firstName "Anthony", "Alice" ... and so on.

There is a special == (exactly equal) operator in VFP that works independantly from SET EXACT or SET ANSI setting. Beware its behavior is different with regular commands and SQL commands. With regular commands it really means 'exactly equal' including the trailing spaces in both of the compared strings. ie:

? 'ABC' == 'ABC ' && false, regardless of SET EXACT

With SQL however (regardless of SET ANSI setting):

select * from myTable where myField == 'A'
select * from myTable where myField == 'A '
select * from myTable where myField == 'A  '

all mean the same and searches for records whose myField content is A (whatever the field size is - trailing spaces on both sides of the comparison are ignored).

Note: I think you can request document topics to be added in stack overflow. VFP documentation has just started and no additions done yet, AFAIK.

Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39