Generate all possible permutations of a given character set with a variable length in t-sql
===

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
