Monday, July 25, 2011

Crystal Reports : Using MID() and INSTR() together

Sooooo, if we were able to write a dynamic MID function, one that could determine where the Lastname started no matter what it was, that would be pretty sweet, right? Because it is in the nature of a human name to have a space between Firstname and Lastname, we can do just that by unleashing our INSTR() "in string" function.

The INSTR() function searches a string for another string. It takes two parameters, like this:

INSTR(string to search, what to search for)

We are going to use it to search for the space in our {USERS.NAME} field.

So, going back to our "Justin Hill" example,

INSTR({USERS.NAME}, " ") = 7 - finds the space between first and lastname

So going back to our original problem, cutting out the Lastname, we can now substitute the starting position in our MID() function with the INSTR() from above like this:

MID({USERS.NAME}, INSTR({USERS.NAME}, " ")) returns " Hill" (note the leading space).

What you really need to do is increment our starting position by 1, because the Lastname starts one character position after the space. Like this:

MID({USERS.NAME}, INSTR({USERS.NAME}, " ") + 1) returns "Hill"

Because the MID function is always being passed the location of the space by INSTR it should reliably "kick out" the Lastname.

Then it is a simple matter to make this code into a Crystal Formula, then use that as your sort field in your Sort Expert.