Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-11 of 11 total

Prefix a string with a specified character to pad it to a desired length

For SQL Server / MSDE databases. This work is licensed under a Creative Commons Attribution 2.5 License.
   1  
   2  CREATE FUNCTION dbo.f_pad_before(@string VARCHAR(255), @desired_length INTEGER, @pad_character CHAR(1))
   3  RETURNS VARCHAR(255) AS  
   4  BEGIN
   5  
   6   -- Prefix the required number of spaces to bulk up the string and then replace the spaces with the desired character
   7   RETURN CASE
   8            WHEN LEN(@string) < @desired_length
   9              THEN REPLACE(SPACE(@desired_length - LEN(@string)), ' ', @pad_character) + @string
  10            ELSE @string
  11          END
  12  
  13  END
  14  GO


Example of usage:
   1  
   2  SELECT dbo.f_pad_before('my string', 20, '-') AS [result], LEN(dbo.f_pad_before('my string', 20, '-')) AS [length]

« Newer Snippets
Older Snippets »
Showing 11-11 of 11 total