No repetition of SQL SERVER code

Asked

Viewed 70 times

-2

I have the following code in sql server. I need to make sure that in the first if it comes out and runs the same instruction that is inside the Else tag not to repeat the code that is inside. How do I do that?

DECLARE @AG_NUM varchar(15)
DECLARE @BCO_NUM VARCHAR(3)
DECLARE @AG_NUM1 varchar(15)
DECLARE @BCO_NUM1 VARCHAR(3)

SELECT TOP 1 @BCO_NUM1 = BcoNUm, @AG_NUM1 = AgNum FROM CONTA_FIN WHERE ContaFinCCorNum = '{AgNum}'

SELECT @AG_NUM = AgNum, @BCO_NUM = BcoNum FROM DUPLICATA where DupNum = '{Duplicata}'

IF (@BCO_NUM is null) OR (@AG_NUM is null)
BEGIN

    UPDATE DUPLICATA SET BcoNum = @BCO_NUM1, AgNUm = @AG_NUM1 WHERE DupNum = '{Duplicata}'

    UPDATE PARC_DOC_FIN SET BcoNum = @BCO_NUM1, AgNum = @AG_NUM1 WHERE ParcDocFinDupNum = '{Duplicata}'

END
ELSE
   -- RESTO DO CODIGO
END.
  • 4

    I didn’t quite understand your question. You want the code piece on else always be executed? It would not be enough to take the else and move the instructions inside the main block?

  • if you want the same command to be executed on both if and Else, it would then be the case to take that command out of the condition blocks....

  • It is difficult to understand what you are wanting. Because you want to execute what is inside the else you don’t even need to have a if. Or you can just use the if for your condition and remove the else.

1 answer

1

You can use label and goto, even not making sense in this context would look like this:

DECLARE @AG_NUM varchar(15)
DECLARE @BCO_NUM VARCHAR(3)
DECLARE @AG_NUM1 varchar(15)
DECLARE @BCO_NUM1 VARCHAR(3)

SELECT TOP 1 @BCO_NUM1 = BcoNUm, @AG_NUM1 = AgNum FROM CONTA_FIN WHERE ContaFinCCorNum = '{AgNum}'

SELECT @AG_NUM = AgNum, @BCO_NUM = BcoNum FROM DUPLICATA where DupNum = '{Duplicata}'

IF (@BCO_NUM is null) OR (@AG_NUM is null)
BEGIN

    UPDATE DUPLICATA SET BcoNum = @BCO_NUM1, AgNUm = @AG_NUM1 WHERE DupNum = '{Duplicata}'

    UPDATE PARC_DOC_FIN SET BcoNum = @BCO_NUM1, AgNum = @AG_NUM1 WHERE ParcDocFinDupNum = '{Duplicata}'

    goto label1 /* a execução continuará logo após o "label1" ... */
END
ELSE
   -- RESTO DO CODIGO
   label1:
   /* exatamente aqui. */
END.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.