views:

33

answers:

1

Hi, I need to zero pad my ID column for putting in drop down combo boxes, example

001 item text

101 item text 2

but if the numbers only went to 80, then we should have

01 item text

80 item text

and so on, since I need to write this and allow tens / thousands / millions of items to go in, I don't know how many 0's i need up front.

I have the following

An SQL Function

-- Create a function to add 0's to the left of a string.
--Usage: 
ALTER FUNCTION [dbo].[LEFTPADNUMERIC]

               (@SourceString VARCHAR(MAX), 

                @FinalLength  INT) 

RETURNS VARCHAR(MAX) 

AS 

  BEGIN 

    RETURN 

      (SELECT Replicate('0',@FinalLength - Len(@SourceString)) + @SourceString) 

  END

And it get’s used like this:

SELECT T.Id, dbo.LEFTPADNUMERIC(Cast(T.Id AS VARCHAR(32)), (Select LEN(CAST(MAX(Id) as varchar(32))) From Task) ) + SPACE(1) + TT.TaskName
FROM Task T
JOIN TaskTranslation TT ON TT.Id = T.Id AND TT.Language = blah blah blah on and on

do you know a better, more efficient way?

Is it going to be calculating max every time, or is sql clever enough to remember that?

Thanks in advance.

+1  A: 

In this case, it would be much easier to add a computed, persisted column to your SQL table that has this padded content:

ALTER TABLE dbo.YourTable
  ADD PaddedID AS RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED

Being a persisted column, the data is actually stored (not calculated on each access), so it will be fast. Now just select this PaddedID column for your drop down box and you're good to go!

marc_s
That sounds good, but what if I end up with numbers that are larger than 5 characters long? then my combo box will end up like this:
adudley
00020, 00010, etc, so we are showing 0's when they are not needed. or when over 5 digits, we end up with them looking out of line :(
adudley
Thanks, using Right in the stored proc cuts execution time by 75%, that's a nice saving :) The function now looks like this: ALTER FUNCTION [dbo].[LEFTPADNUMERIC2] (@Source INT, @FinalLength INT) RETURNS VARCHAR(32) AS BEGIN RETURN (SELECT Right('0000000000000000000' + CAST(@Source AS VARCHAR(32)) , @FinalLength)) END
adudley
@adudley: I choose 5 chars just as a sample - feel free to increase that to 20, if you like :-)
marc_s
@marc_s ahh! but that was the question! how do we make it dynamic, so we only have enough leading zeros, and not too many. And then as more records are added (moving from 99 to 100 for example) then we need to add'another' leading 0, so it all looks nice :)
adudley