document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. DECLARE @VALUE AS VARCHAR(20) = \'ABCD\' --Mention the text which is to be permuted
  2. DECLARE @NoOfChars AS INT = LEN(@VALUE)
  3. DECLARE @Permutations TABLE(VALUE VARCHAR(20)) --Make sure the size of this Value is equal to your input  string length (@Value)
  4.  
  5.  
  6. ;WITH NumTally AS (--Prepare the Tally Table to separate each character of the Value.
  7.   SELECT 1 Num
  8.   UNION ALL
  9.   SELECT
  10.     Num + 1
  11.   FROM
  12.     NumTally
  13.   WHERE
  14.     Num < @NoOfChars
  15. ),Chars AS ( --Separate the Characters
  16. SELECT
  17.   Num,
  18.   SUBSTRING(@VALUE,Num,1) Chr
  19. FROM
  20.   NumTally  
  21. )
  22.  
  23. --Persist the Separated characters.
  24.  
  25. INSERT INTO @Permutations
  26. SELECT Chr FROM Chars
  27.  
  28. --Prepare Permutations
  29.  
  30. DECLARE @i AS INT = 1
  31. WHILE(@i < @NoOfChars)
  32. BEGIN
  33.  
  34.   --Store the Permutations
  35.  
  36.   INSERT INTO @Permutations
  37.   SELECT DISTINCT --Add DISTINCT if required else duplicate Permutations will be generated for Repeated  Chars.
  38.     P1.VALUE + P2.VALUE
  39.   FROM
  40.     (SELECT VALUE FROM @Permutations WHERE LEN(VALUE) = @i) P1
  41.   CROSS JOIN
  42.     (SELECT VALUE FROM @Permutations WHERE LEN(VALUE) = 1) P2
  43.  
  44.   --Increment the Counter.      
  45.   SET @i += 1  
  46.  
  47.   --Delete the Incorrect Lengthed Permutations to keep the table size under control.
  48.   DELETE FROM @Permutations WHERE LEN(VALUE) NOT IN (1,@i)
  49.  
  50. END
  51.  
  52. --Delete InCorrect Permutations.
  53.  
  54. SET @i = 1
  55.  
  56. WHILE(@i <= @NoOfChars)
  57. BEGIN
  58.  
  59.   --Deleting Permutations which has not used "All the Chars of the given Value".
  60.   DELETE
  61.   FROM
  62.     @Permutations
  63.   WHERE
  64.     VALUE NOT LIKE \'%\' + SUBSTRING(@VALUE,@i,1) +\'%\'
  65.  
  66.  
  67.   --Deleting Permutations which have repeated incorrect character.  
  68.   DELETE
  69.   FROM
  70.     @Permutations
  71.   WHERE
  72.     LEN(VALUE) - LEN(REPLACE(VALUE,SUBSTRING(@VALUE,@i,1),\'\')) !=
  73.     LEN(@VALUE) - LEN(REPLACE(@VALUE,SUBSTRING(@VALUE,@i,1),\'\'))
  74.  
  75.   SET @i += 1  
  76.  
  77. END
  78.  
  79. --Selecting the generated Permutations.
  80. SELECT VALUE FROM @Permutations
');