在收到有关可能排列数量的评论后,我意识到字符集的长度和指定的长度应该有非常严格的限制。
鉴于允许的长度非常小,我认为在我的脚本中使用条件没有什么害处......就像这样:
DECLARE
@string NVARCHAR(40), --limit the length of the character set to 40
@length INT -- the limit for this is in a validation check below
SELECT
@string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
@length = 2
IF (@length < 1 OR @length > 4) BEGIN
RAISERROR('Invalid length specified. This function only supports lengths from 1 to 4', 16, 1)
END
DECLARE @Chars TABLE (
C CHAR(1) PRIMARY KEY
)
;WITH numbers AS (
SELECT TOP(LEN(@string)) number
FROM master..spt_values
WHERE type = 'P'
AND number != 0
)
INSERT @Chars (
C
)
SELECT
C = SUBSTRING(@string, number, 1)
FROM numbers
IF (@length = 1) BEGIN
SELECT C FROM @Chars ORDER BY C
END ELSE IF (@length = 2) BEGIN
SELECT A.C + B.C
FROM @Chars A, @Chars B
ORDER BY A.C, B.C
END ELSE IF (@length = 3) BEGIN
SELECT A.C + B.C + C.C
FROM @Chars A, @Chars B, @Chars C
ORDER BY A.C, B.C, C.C
END ELSE IF (@length = 4) BEGIN
SELECT A.C + B.C + C.C + D.C
FROM @Chars A, @Chars B, @Chars C, @Chars D
ORDER BY A.C, B.C, C.C, D.C
END