Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

PadLeft Function - SQL Server

RSS
Modified on Wed, Dec 29, 2010, 1:56 PM by Administrator Categorized as SQL Server
{copytext|src}
create function [dbo].[PadLeft]
    (
     @input     int 
    ,@width     int 
    ,@pad       char(1) 
    ) returns varchar(max) as begin
/*
declare
     @input int = 1
    ,@width int = 3 
    ,@pad char(1) = '0' 
*/
    
declare @len int = case when @input = 0 then 1 else ceiling(LOG10(@input+1)) end

declare @result varchar(max) = REPLICATE(@pad, @width - @len) + CONVERT(varchar(20), @input)
/*
select result = @result
*/
return @result
end

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.