Advertisement
Willcode4cash

URL Shortening SQL Encode and Decode functions

Aug 18th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.36 KB | None | 0 0
  1. CREATE FUNCTION dbo.Decode (@encodedId NVARCHAR(50))
  2.   RETURNS INT
  3.   AS
  4.   BEGIN
  5.  
  6.     DECLARE @alphabet   nvarchar(36) = 'abcdefghijklmnopqrstuvwxyz0123456789',
  7.             @base       INT,
  8.             @decodedId  INT = 0,
  9.             @len        INT,
  10.             @pos        INT = 1,
  11.             @letter     NVARCHAR(10)
  12.  
  13.     SET     @len = LEN(@encodedId)
  14.     SET     @base = LEN(@alphabet)
  15.  
  16.     WHILE(@pos <= @len)
  17.       BEGIN
  18.         SET @letter = SUBSTRING(@encodedId, @pos, 1)
  19.         SET @decodedId = (@decodedId * @base) + CHARINDEX(@letter, @alphabet)
  20.         SET @pos += 1
  21.       END
  22.  
  23.     RETURN @decodedId
  24.  
  25.   END
  26. GO
  27.  
  28. CREATE FUNCTION dbo.Encode (@id INT)
  29.   RETURNS NVARCHAR(50)
  30.   AS
  31.   BEGIN
  32.  
  33.     DECLARE @alphabet   nvarchar(36) = 'abcdefghijklmnopqrstuvwxyz0123456789',
  34.             @base       int,
  35.             @pos        int,
  36.             @result     nvarchar(50) = '',
  37.             @encodedId  nvarchar(50) = ''
  38.  
  39.     SET     @base = LEN(@alphabet)
  40.  
  41.     IF(@id = 0)
  42.       BEGIN
  43.         SET @result = SUBSTRING(@alphabet, 1, 1)
  44.       END
  45.     ELSE
  46.       BEGIN
  47.         WHILE(@id > 0)
  48.           BEGIN
  49.             SET @pos = @id % @base
  50.             SET @encodedId += SUBSTRING(@alphabet, @pos, 1)
  51.             SET @id = @id / @base
  52.           END
  53.         SET @result = REVERSE(@encodedId)
  54.       END
  55.  
  56.     RETURN @result
  57.  
  58.   END
  59. GO
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement