Advertisement
Guest User

Untitled

a guest
Feb 17th, 2013
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.41 KB | None | 0 0
  1. DECLARE @INPUT nvarchar(100) = 'abbccc';
  2.    
  3. WITH nums AS
  4. (
  5.    SELECT n = 1           -- base case starting at 1
  6.    
  7.    UNION ALL
  8.    
  9.    SELECT n = n+1         -- recursive case:  next number = 2, 3, ... len(@input)
  10.    FROM nums
  11.    WHERE n < len(@INPUT)  -- stop and don't run if n equal the len(@input)
  12. )
  13. ,perms AS
  14. (
  15.    SELECT                                      -- base case for recursion
  16.       string = CAST(''     AS nvarchar(100)),  -- string we are generating, start as empty string
  17.       remain = CAST(@INPUT AS nvarchar(100)),  -- remaining characters to append to our string
  18.       pos    = n                               -- position of next character in remaining string to append to base case
  19.    FROM nums
  20.    
  21.    UNION ALL
  22.    
  23.    -- recursive case where we append 1 character per step
  24.    SELECT
  25.       -- append character at position pos to base string
  26.       string = CAST(string + SUBSTRING(remain,pos,1) AS nvarchar(100)),
  27.       -- remove character we added from remaining characters
  28.       remain = CAST(stuff(remain,pos,1,'') AS nvarchar(100)),
  29.       -- all possible positions of remaining characters
  30.       pos    = nums.n
  31.    FROM perms, nums
  32.    -- only look at possible valid positions
  33.    -- this forces the recursion to terminate when remain is empty
  34.    WHERE pos <= len(remain)
  35. )
  36. SELECT DISTINCT string
  37. FROM perms
  38. WHERE len(string) = len(@INPUT)
  39. ORDER BY string
  40. OPTION (maxrecursion 10000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement