3

我编写了下面的脚本来生成指定字符集的所有可能排列。

有没有办法有效地做到这一点,同时允许在运行时指定长度?

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
4

2 回答 2

2

如果您使用的是 SQL Server 2005 或更高版本,您可以尝试递归 CTE:

DECLARE @length int;
SET @length = 3;

WITH expanded AS (
  SELECT
    C = SUBSTRING(@string, N, 1)
  FROM numbers
  WHERE number BETWEEN 1 AND LEN(@string)
),
permutations AS (
  SELECT
    S = CAST(C AS nvarchar(max)),
    L = 1
  FROM expanded
  UNION ALL
  SELECT
    S = S + C,
    L = L + 1
  FROM permutations p
  CROSS JOIN expanded e
  WHERE L < @length
)
SELECT *
FROM permutations
WHERE L = @length
;

numbers是一个数字辅助表,用于将字符串扩展为单个字符的列。

如果不进行更多更改,此查询将使用@length高达 100 的值而不会出现问题。如果您想要更大长度的排列,则需要附加此行:

OPTION (MAXRECURSION n)

其中n是一个从 0 到 32767 的整数值,表示递归 CTE 的最大迭代次数,上面提到的 100 是默认值。Nil 实际上意味着没有限制,应该谨慎使用。

您可以在 SQL Fiddle尝试此查询(并使用它),在那里我将其减少@string到只有 8 个字符(以便能够指定更多不同的值@length而不使查询返回太多行)并将numbers表定义为系统表master..spt_values的子集。

于 2012-07-18T20:34:03.020 回答
0

在收到有关可能排列数量的评论后,我意识到字符集的长度和指定的长度应该有非常严格的限制。

鉴于允许的长度非常小,我认为在我的脚本中使用条件没有什么害处......就像这样:

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
于 2012-07-18T21:40:04.923 回答