0
I have to perform a validation on a Trigger on sql server the rule is: if cnpj is != 0 and does not exist in another record continue;
however cnpj can come with 0 or 000 or 0000000 or 00, which would give in the same...
I am currently doing the validation below however, I was asked to change the validation != 0 for something more "elegant", someone has some idea of how I can do this?
IF 0 != CONVERT(bigint,(SELECT CGC_CPF FROM inserted))
BEGIN
if EXISTS(SELECT * FROM CADASTRO_CLI_FOR A
LEFT JOIN FILIAIS B ON A.COD_CLIFOR=B.COD_FILIAL
WHERE A.CGC_CPF=@CNPJ
AND B.INDICA_ARMAZEM =0)
begin
select @errno = 30002,
@errmsg = 'Impossível Incluir #FORNECEDORES #porque CNPJ #ja existe.'
goto error
end
end
return
If there is more than one line in the INSERTED table, there will be an error in the trigger procedure. Suggested reading: https://social.technet.microsoft.com/wiki/pt-br/contents/articles/38010.armadilhas-na-programacao-de-procedurals_trigger.aspx
– José Diz
Could you post the trigger procedure code? // What would be "more elegant"?
– José Diz
the Trigger is pretty big plus this is the part where I need to refactor. More elegant would be a better way to do this test;
– João Rafael Colombo
I understood the question of Insert with more lines, but how do I need to get the cnpj of INSERTED I must make a loop to validate all lines? because it would have to validate all lines in INSERTED, or another solution?
– João Rafael Colombo
The validation could not be done in the application? // What is the origin of the contents of the variable @CNPJ?
– José Diz
Unfortunately not, the software is third party, and we have more than one software persisting in the same bank and some are legacy software without this rule, they could circumvent this validation, for this reason we need to apply directly in DB
– João Rafael Colombo
CONSIDERING: (1) the need for trigger procedure to treat more than one line; (2) that the current trigger procedure is programmed to treat only one line at a time; (3) the impossibility of suggesting set-based solution by ignorance (on my part) from the source code of the trigger procedure; EVALUATE the implementation of the "Simulation for each Row with cursor" solution proposed in https://social.technet.microsoft.com/wiki/pt-br/contents/articles/40005.armadilhas-na-programca-procedural.
– José Diz