I have a scenario that I need to sort my records where:
Did the child inherit the surname of the father and / or his mother?
Notice in the picture that if one of the child's last names exists in the parent's name the PAI?
field gets true. Likewise for the MAE?
field.
Scenario Building
CREATE TABLE USUARIOS
(CODIGO INT IDENTITY,
NOME VARCHAR(255),
MAE VARCHAR(255),
PAI VARCHAR(255)
)
CREATE CLUSTERED INDEX PK_CODIGO ON USUARIOS (CODIGO);
CREATE INDEX NOME ON USUARIOS (NOME, CODIGO);
CREATE INDEX MAE ON USUARIOS (MAE, CODIGO) INCLUDE(NOME);
CREATE INDEX PAI ON USUARIOS (PAI, CODIGO) INCLUDE(NOME);
GO
INSERT INTO USUARIOS (NOME, MAE, PAI) VALUES('ADRIANA ARAUJO DIAS','JOAO WILSON ARAUJO','JOSELIA PEREIRA ARAUJO')
INSERT INTO USUARIOS (NOME, MAE, PAI) VALUES('NICOLAS PEDRO SILVA','SERGIO LUIZ SILVA JUNIOR','THAIS BATISTA DOS SANTOS SILVA')
INSERT INTO USUARIOS (NOME, MAE, PAI) VALUES('CARLOS JOSE DOS SANTOS ANJO','ACACIO APARECIDO ANJO DA SILVA','JULIANA ARAUJO DOS SANTOS ANJO')
INSERT INTO USUARIOS (NOME, MAE, PAI) VALUES('NICOLAY RIBEIRO DANTAS','RICARDO VICENTE RIBEIRO','JOZEILDA LUIS ENCARNACAO')
INSERT INTO USUARIOS (NOME, MAE, PAI) VALUES('MARIA DA SILVA MATTOS','FRANKLIN DE OLIVEIRA','BRUNA CATARINA DA SILVA MATTOS')
INSERT INTO USUARIOS (NOME, MAE, PAI) VALUES('CREUSA MARIA MORAES','GELSON DO ESPIRITO SANTO','FATIMA APARECIDA DOS SANTOS')
INSERT INTO USUARIOS (NOME, MAE, PAI) VALUES('DAVID BRADAO BORGES','EMERSON DOS SANTOS BORGES','DAYANE EVANGELISTA ACACIO BORGES')
INSERT INTO USUARIOS (NOME, MAE, PAI) VALUES('LUIZ ADAO SANTOS DA SILVA','WESLEY GONCALVES SILVA','IZABEL BRANDAO DA SILVA')
GO
SELECT CODIGO, NOME, PAI, MAE,
(SELECT COUNT(*) FROM USUARIOS T1
WHERE T1.CODIGO = TAB.CODIGO AND
CHARINDEX(SUBSTRING(NOME, CHARINDEX(' ', NOME)+1, CHARINDEX(' ', NOME, CHARINDEX(' ', NOME)+1) - CHARINDEX(' ', NOME)-1), PAI) > 0 --FUNCIONA PARA O PRIMEIRO SOBRENOME (PAI)
) AS [PAI?],
(SELECT COUNT(*) FROM USUARIOS T1
WHERE T1.CODIGO = TAB.CODIGO AND
CHARINDEX(SUBSTRING(NOME, CHARINDEX(' ', NOME)+1, CHARINDEX(' ', NOME, CHARINDEX(' ', NOME)+1) - CHARINDEX(' ', NOME)-1), MAE) > 0 --FUNCIONA PARA O PRIMEIRO SOBRENOME (MÃE)
) AS [MAE?]
FROM USUARIOS TAB
As far as I got, with the above query, I can at least check with the first surname, but how to do this query to verify all surnames?
Note: The names I submitted are fictitious. Do not consider if they coincide with real people.