Friday, May 19, 2006

SQL Server Leading Zeros for CHAR Type

declare @DirectiveNumber char(6)
declare @DirLength int



SET @DirectiveNumber = (SELECT DirectiveNumber FROM dbo.tblPlants WHERE PlantId = '1201')

--UPDATE dbo.tblPlants SET DirectiveNumber =
SET @DirectiveNumber = @DirectiveNumber + 1

Select @DirLength = LEN(@DirectiveNumber)

IF (@DirLength = 1)
SET @DirectiveNumber = '00000' + @DirectiveNumber
IF (@DirLength = 2)
SET @DirectiveNumber = '0000' + @DirectiveNumber
IF (@DirLength = 3)
SET @DirectiveNumber = '000' + @DirectiveNumber
IF (@DirLength = 4)
SET @DirectiveNumber = '00' + @DirectiveNumber
IF (@DirLength = 5)
SET @DirectiveNumber = '0' + @DirectiveNumber

UPDATE dbo.tblPlants SET DirectiveNumber = @DirectiveNumber WHERE PlantId = '1201'

SELECT @DirectiveNumber

No comments: