SHARE
TWEET

string permutations

a guest Jan 9th, 2013 148 Never
  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)
RAW Paste Data
Top