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-12 of 12 total

Convert an integer from Base 10 to another Base (e.g. Hex or Binary)

@base can be anything from 2 to 36 (because then we can stick to the alphanumerics 0 to 9 and A to Z).
This work is licensed under a Creative Commons Attribution 2.5 License.
CREATE FUNCTION dbo.f_convert_from_base10
  (@num INT, @base TINYINT)
RETURNS VARCHAR(255) AS 
BEGIN 

  -- Declarations
  DECLARE @string VARCHAR(255)
  DECLARE @return VARCHAR(255)
  DECLARE @finished BIT
  DECLARE @div INT
  DECLARE @rem INT
  DECLARE @char CHAR(1)

  -- Initialise
  SELECT @string   = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  SELECT @return   = CASE WHEN @num <= 0 THEN '0' ELSE '' END
  SELECT @finished = CASE WHEN @num <= 0 THEN 1 ELSE 0 END
  SELECT @base     = CASE WHEN @base < 2 OR @base IS NULL THEN 2 WHEN @base > 36 THEN 36 ELSE @base END

  -- Loop
  WHILE @finished = 0
  BEGIN

    -- Do the maths
    SELECT @div = @num / @base
    SELECT @rem = @num - (@div * @base)
    SELECT @char = SUBSTRING(@string, @rem + 1, 1)
    SELECT @return = @char + @return
    SELECT @num = @div

    -- Nothing left?
    IF @num = 0 SELECT @finished = 1

  END

  -- Done
  RETURN @return

END
GO


Example of usage:
SELECT 255 AS [decimal], dbo.f_convert_from_base10(255, 16) AS [hex], dbo.f_convert_from_base10(255, 2) AS [binary], dbo.f_convert_from_base10(255, 36) AS [base 36]

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.
CREATE FUNCTION dbo.f_pad_before(@string VARCHAR(255), @desired_length INTEGER, @pad_character CHAR(1))
RETURNS VARCHAR(255) AS  
BEGIN

 -- Prefix the required number of spaces to bulk up the string and then replace the spaces with the desired character
 RETURN CASE
          WHEN LEN(@string) < @desired_length
            THEN REPLACE(SPACE(@desired_length - LEN(@string)), ' ', @pad_character) + @string
          ELSE @string
        END

END
GO


Example of usage:
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-12 of 12 total