Integration Points

Extending Corporate Data …

#47 Simple T-SQL UDF Providing Leading Zeroes

leave a comment »

This is simply a conversion of this post to an UDF that provides leading zero support on an int field & returns a varchar(20).

Create FUNCTION [dbo].[udf_LeadingZeroes]
(     
        @FieldValue        int
    ,   @LeadZeroCount     int
)

RETURNS varchar(20) AS

BEGIN

	Declare @ReturnString   varchar(20)
 
	Set @ReturnString = RIGHT(REPLICATE('0', @LeadZeroCount) + CONVERT(varchar(20), @FieldValue), @LeadZeroCount)
	
	RETURN @ReturnString

END

-- Usage 
Select dbo.udf_LeadingZeroes(ColName,4) as ColName_With_LeadingZeroes 
From SomeTable 

Advertisement

Written by dmgorman

October 20, 2011 at 4:46 pm

Posted in SQL

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.