This SQL will compute permutations without repetition:
WITH recurse(Result, Depth) AS ( SELECT CAST(Value AS VarChar(100)), 1 FROM MyTable UNION ALL SELECT CAST(r.Result + '+' + a.Value AS VarChar(100)), r.Depth + 1 FROM MyTable a INNER JOIN recurse r ON CHARINDEX(a.Value, r.Result) = 0 ) SELECT Result FROM recurse WHERE Depth = (SELECT COUNT(*) FROM MyTable) ORDER BY Result
If MyTable contains 9 lines, it will take some time to calculate, but it will return 362,880 lines.
Update with explanation:
The WITH used to define the expression of a recursive shared table . In fact, the WITH statement is looped several times, executing UNION until the recursion is complete.
The first part of SQL defines the start records. Assuming that there are three lines with the names "A", "B" and "C" in MyTable , this will produce these lines:
Result Depth
Then the following SQL block executes the first level of recursion:
SELECT CAST(r.Result + '+' + a.Value AS VarChar(100)), r.Depth + 1 FROM MyTable a INNER JOIN recurse r ON CHARINDEX(a.Value, r.Result) = 0
These are all the records created so far (which will be in the recurse table), and again joins them with all the records in MyTable . The ON clause filters the list of records in MyTable to return only those that do not exist in this row permutation. This will result in the following lines:
Result Depth
Then the recursion loops again produce the following lines:
Result Depth
At this point, recursion stops because UNION does not create more rows, because CHARINDEX will always be 0 .
The last SQL filters all the resulting rows, where the calculated Depth column matches # records in MyTable . This ejects all rows except those created by the last recursion depth. Thus, the end result will be the following lines:
Result