如何在SQL中生成随机字符串

时间:2010-12-29 22:25:54

标签: tsql

如何生成随机字符串? 我写了以下内容,结果只给了我一封信!

declare @alphaCount int
set @alphaCount =  @alphaCount +1
CHAR(@alphaCount)

提前致谢!

4 个答案:

答案 0 :(得分:6)

这将为您提供指定格式的10,000行。

DECLARE @Numbers  TABLE
(
n INT PRIMARY KEY
);


WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),   --2
        E02(N) AS (SELECT 1 FROM E00 a, E00 b), --4
        E04(N) AS (SELECT 1 FROM E02 a, E02 b), --16
        E08(N) AS (SELECT 1 FROM E04 a, E04 b), --256
        E16(N) AS (SELECT 1 FROM E08 a, E08 b)  --65,536
INSERT INTO @Numbers
SELECT TOP 10000 ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM E16        

SELECT CAST((SELECT TOP 20 CHAR(CASE
                                  WHEN Abs(Checksum(Newid()))%2 = 0 THEN 65
                                  ELSE 97
                                END + Abs(Checksum(Newid()))%26)
             FROM   @Numbers n1
             WHERE  n1.n >= -n2.n /*So it gets re-evaluated for each row!*/
             FOR XML PATH('')) AS CHAR(20))
FROM   @Numbers n2  

答案 1 :(得分:1)

使用随机单词列表填写临时表。然后使用CROSS JOIN将每个单词与其他单词组合起来,轻松获取大量数据。

select l.word+' '+r.word from #Words as l
cross join #Words as r

答案 2 :(得分:1)

This procedure会奏效。您可能需要使用它创建一个函数,但它有正确的想法。

答案 3 :(得分:0)

这应该是如何

的诀窍
DECLARE @length         Integer
DECLARE @return         VarChar(1000)
DECLARE @index          Integer
DECLARE @value          Integer

SET @length = 12
SET @return = '';

IF @length > 1000
    SET @length = 1000;

IF @length <= 0
    SELECT @return;

SET @index = 0;

WHILE @index < @length
BEGIN
    SET @value = (64 * RAND()) + 32;
    SET @return = @return + CHAR(@value);

    SET @index = @index + 1;
END 

SELECT @return;

如果你想让它成为用户定义的功能,我喜欢本文中的“steve”选项。 here