DECLARE @VALUE AS VARCHAR(20) = \'ABCD\' --Mention the text which is to be permuted
DECLARE @NoOfChars AS INT = LEN(@VALUE)
DECLARE @Permutations TABLE(VALUE VARCHAR(20)) --Make sure the size of this Value is equal to your input string length (@Value)
;WITH NumTally AS (--Prepare the Tally Table to separate each character of the Value.
SELECT 1 Num
UNION ALL
SELECT
Num + 1
FROM
NumTally
WHERE
Num < @NoOfChars
),Chars AS ( --Separate the Characters
SELECT
Num,
SUBSTRING(@VALUE,Num,1) Chr
FROM
NumTally
)
--Persist the Separated characters.
INSERT INTO @Permutations
SELECT Chr FROM Chars
--Prepare Permutations
DECLARE @i AS INT = 1
WHILE(@i < @NoOfChars)
BEGIN
--Store the Permutations
INSERT INTO @Permutations
SELECT DISTINCT --Add DISTINCT if required else duplicate Permutations will be generated for Repeated Chars.
P1.VALUE + P2.VALUE
FROM
(SELECT VALUE FROM @Permutations WHERE LEN(VALUE) = @i) P1
CROSS JOIN
(SELECT VALUE FROM @Permutations WHERE LEN(VALUE) = 1) P2
--Increment the Counter.
SET @i += 1
--Delete the Incorrect Lengthed Permutations to keep the table size under control.
DELETE FROM @Permutations WHERE LEN(VALUE) NOT IN (1,@i)
END
--Delete InCorrect Permutations.
SET @i = 1
WHILE(@i <= @NoOfChars)
BEGIN
--Deleting Permutations which has not used "All the Chars of the given Value".
DELETE
FROM
@Permutations
WHERE
VALUE NOT LIKE \'%\' + SUBSTRING(@VALUE,@i,1) +\'%\'
--Deleting Permutations which have repeated incorrect character.
DELETE
FROM
@Permutations
WHERE
LEN(VALUE) - LEN(REPLACE(VALUE,SUBSTRING(@VALUE,@i,1),\'\')) !=
LEN(@VALUE) - LEN(REPLACE(@VALUE,SUBSTRING(@VALUE,@i,1),\'\'))
SET @i += 1
END
--Selecting the generated Permutations.
SELECT VALUE FROM @Permutations