
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F_PAD_STRING]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[F_PAD_STRING]
GO  
GO
CREATE FUNCTION [dbo].[F_PAD_STRING](
               @string_unpadded VARCHAR(100)
             , @pad_char        VARCHAR(1)
             , @pad_count       TINYINT
             , @pad_pattern     INT)
RETURNS VARCHAR(100)
WITH SCHEMABINDING AS
     BEGIN
         DECLARE @string_padded VARCHAR(100);
		  
         
		 if @pad_pattern=0
		 begin
			set @string_padded =  REPLICATE(@pad_char, @pad_count-LEN(@string_unpadded)) + @string_unpadded --pad left 
			return @string_padded;
		 end
		 --------------------------------------------------------------------------------------------------------------------
		 if @pad_pattern=1
		 begin
			set @string_padded =  @string_unpadded + REPLICATE(@pad_char, @pad_count-LEN(@string_unpadded)) --pad right 
			return @string_padded;
		 end
		 --------------------------------------------------------------------------------------------------------------------
		 if @pad_pattern=2
		 begin
			set @string_padded =   LEFT(@string_unpadded, FLOOR(LEN(@string_unpadded) / 2)) 
										+ REPLICATE(@pad_char, @pad_count-LEN(@string_unpadded)) 
										+ RIGHT(@string_unpadded, LEN(@string_unpadded) - FLOOR(LEN(@string_unpadded) / 2))

			return @string_padded;
		 end
		 --------------------------------------------------------------------------------------------------------------------
		 if @pad_pattern=3
		 begin
			set @string_padded =  REPLICATE(@pad_char, FLOOR((@pad_count - LEN(@string_unpadded)) / 2)) + @string_unpadded + REPLICATE(@pad_char, (@pad_count-LEN(@string_unpadded))-FLOOR((@pad_count - LEN(@string_unpadded)) / 2))
			return @string_padded;
		 end
		 
		 --------------------------------------------------------------------------------------------------------------------

         RETURN @string_padded;
     END;
GO