Home > OS >  Can you simplify how to code this problem?
Can you simplify how to code this problem?

Time:11-15

Suppose that I work with an external company that sends me folios for an invoice every time they are due. For example, we started from folio 1 to 999. As we were very successful, we reached invoice 999, for which the entity gave me new billing codes ranging from 1000 to 10000. This is the base, so for this I have created a table that will store these folios as follows, idEntity (refers to the foreign external entity), folioInicio, folioTermino, folioActual. The current folio field has the last folio used by the invoice, then through a trigger every time a product or service is invoiced, it increases and changes the field in the table.

This is the base, but in reality that folio when printing it in a pdf document or in the operation is transformed into a 7-digit alphanumeric by prefixing an F. For example, folio 1 would be F000001. and so on.

For this, create a function that is executed in the trigger as follows.

CREATE FUNCTION dbo.GenerateFolioNumber(@FOLIO BIGINT)
RETURN VARCHAR(7)
ACE
START
DECLARE @NROFOLIO VARCHAR(7);
IF(LEN(CONVERT(VARCHAR(7), @FOLIO)) = 1) set @NROFOLIO ='F00000'  CONVERT(VARCHAR(7), @FOLIO);
IF(LEN(CONVERT(VARCHAR(7), @FOLIO)) = 2) set @NROFOLIO ='F0000'  CONVERT(VARCHAR(7), @FOLIO);
IF(LEN(CONVERT(VARCHAR(7), @FOLIO)) = 3) set @NROFOLIO ='F000' CONVERT(VARCHAR(7), @FOLIO);
IF(LEN(CONVERT(VARCHAR(7), @FOLIO)) = 4) set @NROFOLIO ='F00' CONVERT(VARCHAR(7), @FOLIO);
IF(LEN(CONVERT(VARCHAR(7), @FOLIO)) = 5) set @NROFOLIO ='F0' CONVERT(VARCHAR(7), @FOLIO);
IF(LEN(CONVERT(VARCHAR(7), @FOLIO)) = 6) set @NROFOLIO ='F' CONVERT(VARCHAR(7), @FOLIO);
RETURN @NROFOLIO;
END;

The thing is that so many IFs seem redundant to me, and I don't have much experience programming SQL but it seems to me that maybe it could be solved in another way, that's why I turn to this community to listen to their experience and see if there is another way to do this.

CodePudding user response:

Perhaps concat() and right()

Declare @FOLIO bigint = 27

Select 'F' right(concat('0000000',@FOLIO),6)

Results

F000027

For the Function

ALTER Function dbo.GenerateFolioNumber(@FOLIO BIGINT)
Returns varchar(7)
Begin
    Return 'F' right(concat('0000000',@FOLIO),6)
End

CodePudding user response:

Lots of options here, another way you could approach this is using:

declare @folio bigint = 123;
select Concat('F', Replicate('0', 6-Len(@folio)), @folio);

Also, you don't share how you are using the function however if in a trigger, and potentially against many rows, consider a table-valued function instead of a scalar function.

  • Related