declare @input nvarchar(100) = 'abbccc'; with nums as ( select n = 1 -- base case starting at 1 union all select n = n+1 -- recursive case: next number = 2, 3, ... len(@input) from nums where n < len(@input) -- stop and don't run if n equal the len(@input) ) ,perms as ( select -- base case for recursion string = cast('' as nvarchar(100)), -- string we are generating, start as empty string remain = cast(@input as nvarchar(100)), -- remaining characters to append to our string pos = n -- position of next character in remaining string to append to base case from nums union all -- recursive case where we append 1 character per step select -- append character at position pos to base string string = cast(string + substring(remain,pos,1) as nvarchar(100)), -- remove character we added from remaining characters remain = cast(stuff(remain,pos,1,'') as nvarchar(100)), -- all possible positions of remaining characters pos = nums.n from perms, nums -- only look at possible valid positions -- this forces the recursion to terminate when remain is empty where pos <= len(remain) ) select distinct string from perms where len(string) = len(@input) order by string option (maxrecursion 10000)