I have written the script below to generate all possible permutations of a specified set of characters.
Is there a way to efficiently do this while allowing the length to be specified at runtime?
DECLARE @string NVARCHAR(MAX)
SELECT @string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
DECLARE @Chars TABLE (
C CHAR(1) PRIMARY KEY
)
DECLARE @N INT
SET @N = 1
WHILE @N <= LEN(@string) BEGIN
INSERT @Chars (
C
) VALUES (
SUBSTRING(@string, @N, 1)
)
SET @N = @N + 1
END
--SELECT * FROM @Chars
SELECT
A.C + B.C + C.C
FROM @Chars A, @Chars B, @Chars C
ORDER BY
A.C,
B.C,
C.C
After receiving comments related to the number of possible permutations, I realized that there should be very tight limits on the length of the character set as well as the specified length.
Given that the allowable length would be extremely small, I see no harm in using a condition in my script… like this: