By reading this comment of yours :
In the DB I keep the names and surnames in a pure variable GONZALEZ
PEREZ JUAN GABRIEL
in this way.
I must say that the solution to this question is one: urgently redesign your data model. The error is that, because you can not use a single column to save everything together with the name and surname .
The difficulty you are having now to want to separate both data is the result of not having separated them when designing the database. It is impossible to create an algorithm or function that differentiates your first and last name in such a design, because:
- It is impossible to know how many words have all the names and surnames that are going to be stored in the database.
- because there are names that seem surnames and surnames that look like names
- because it is impossible to know where the name ends and the last name begins
- because ...
- because ...
Later there will be other complications ... I want to see the face you are going to put when asked for a list organized by the first surname, or by the second surname ... OMG !!! And the table has 10 million records! How can I normalize it now? How will I know in data like this where the name ends and the surname begins: José Martín Pérez
and José Martín Pérez
... it turns out that in the first one your name is José Martín
, but in the second your name is José
and their last names are Martín Perez
... Normalizing when there are several thousand records is going to be complicated.
Or when they ask you for a list with surnames that begin with the letter B
... Or anything else that may be necessary in the future.
Solution
Redesign the data to normalize it , creating one or two columns for the name, and one or two columns for the surnames, as the case may be.
-
nombre
-
primer_apellido
-
segundo_apellido
--optional