I have the following table A:
id
----
1
2
12
123
1234
I need to left-pad the id
values with zero\'s:
id
----
0
Create Function :
Create FUNCTION [dbo].[PadLeft]
(
@Text NVARCHAR(MAX) ,
@Replace NVARCHAR(MAX) ,
@Len INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @var NVARCHAR(MAX)
SELECT @var = ISNULL(LTRIM(RTRIM(@Text)) , '')
RETURN RIGHT(REPLICATE(@Replace,@Len)+ @var, @Len)
END
Example:
Select dbo.PadLeft('123456','0',8)
I created a function:
CREATE FUNCTION [dbo].[fnPadLeft](@int int, @Length tinyint)
RETURNS varchar(255)
AS
BEGIN
DECLARE @strInt varchar(255)
SET @strInt = CAST(@int as varchar(255))
RETURN (REPLICATE('0', (@Length - LEN(@strInt))) + @strInt);
END;
Use: select dbo.fnPadLeft(123, 10)
Returns: 0000000123
Old post, but maybe this helps someone out:
To complete until it ends up with 4 non-blank characters:
SELECT RIGHT ('0000'+COLUMNNAME, 4) FROM TABLENAME;
To complete until 10:
SELECT RIGHT ('0000000000'+COLUMNNAME, 10) FROM TABLENAME;
In case the column is numeric, convert it to varchar first with such code:
Select RIGHT('0000'+Convert(nvarchar(20), COLUMNNAME), 4)
From TABLENAME
And to complete until 10 with a numeric field:
SELECT RIGHT ('0000000000'+Convert(nvarchar(20), COLUMNNAME), 10) FROM TABLENAME;
This is what I normally use when I need to pad a value.
SET @PaddedValue = REPLICATE('0', @Length - LEN(@OrigValue)) + CAST(@OrigValue as VARCHAR)
I needed this in a function on SQL server and adjusted Patrick's answer a bit.
declare @dossierId int = 123
declare @padded_id varchar(7)
set @padded_id = REPLACE(
SPACE(7 - LEN(@dossierId)) + convert(varchar(7), @dossierId),
SPACE(1),
'0')
SELECT @dossierId as '@dossierId'
,SPACE(LEN(@dossierId)) + convert(varchar(7)
,@dossierId) as withSpaces
,@padded_id as '@padded_id'