Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

string permutations

By: a guest on Jan 9th, 2013  |  syntax: SQL  |  size: 0.55 KB  |  views: 121  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. DECLARE @a nvarchar(100) = 'abbccc';
  2.    
  3.     WITH a AS(SELECT 1 n UNION ALL SELECT n+1 FROM a WHERE n<len(@a))
  4.     ,b AS
  5.     (
  6.        SELECT CAST('' AS nvarchar(100)) s, CAST(@a AS nvarchar(100)) r, n p
  7.        FROM a
  8.        UNION ALL
  9.        SELECT  
  10.           CAST(s+SUBSTRING(r,p,1) AS nvarchar(100)),
  11.           CAST(SUBSTRING(r,1,p-1)+SUBSTRING(r,p+1,999) AS nvarchar(100)),
  12.           n
  13.        FROM a,b
  14.        WHERE p<=len(r)
  15.     )
  16.     SELECT DISTINCT s
  17.     FROM b
  18.     WHERE len(s) = len(@a)
  19.     ORDER BY s
  20.     OPTION (maxrecursion 10000)