将while循环值作为SQL Server中的多行返回,而不是多个结果集

时间:2016-08-22 19:39:02

标签: sql sql-server tsql

我有以下T-SQL,用于生成一些随机值:

DECLARE @cnt INT = 0;

WHILE @cnt < 100
BEGIN

select
    Random_String =
    substring(x,(abs(checksum(newid()))%36)+1,1)+       
    substring(x,(abs(checksum(newid()))%36)+1,1)+
    substring(x,(abs(checksum(newid()))%36)+1,1)

from
          (select x='0123456789ABCDEFGHJKLMNPQRSTUWXYZ%#-=+') a

          SET @cnt = @cnt + 1;
END;

这很好用,除了每个字符串都返回,看起来像是一个独立的结果集。

有没有办法重构该查询以将每个值作为同一结果集中的一行返回?

环境是MS SQL Server 2008。

谢谢!

2 个答案:

答案 0 :(得分:7)

执行此类操作的最佳方法是忘记在t-sql中循环。使用数字或计数表是一种更好的方法。

WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a cross join E1 b), --10E+2 or 100 rows
    cteTally(N) AS 
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E2
    )

select
    Random_String =
    substring(x,(abs(checksum(newid()))%36)+1,1)+       
    substring(x,(abs(checksum(newid()))%36)+1,1)+
    substring(x,(abs(checksum(newid()))%36)+1,1)

from
(select x='0123456789ABCDEFGHJKLMNPQRSTUWXYZ%#-=+') a
cross join cteTally t
where t.N < = 100

答案 1 :(得分:2)

以下是使用计数表的方法:

;With Tally (N) As
(
    Select  0   Union All
    Select  1   Union All
    Select  2   Union All
    Select  3   Union All
    Select  4   Union All
    Select  5   Union All
    Select  6   Union All
    Select  7   Union All
    Select  8   Union All
    Select  9
), Numbers (N) As
(
    Select      Row_Number() Over (Order By A.N) Num
    From        Tally   A   --  10
    Cross Join  Tally   B   --  100
    Cross Join  Tally   C   --  1000
    Cross Join  Tally   D   --  10000
    Cross Join  Tally   E   --  100000
), LookupString (X) As
(
    Select  '0123456789ABCDEFGHJKLMNPQRSTUWXYZ%#-=+'
)
Select      Random_String = substring(x,(abs(checksum(newid()))%36)+1,1)+       
                            substring(x,(abs(checksum(newid()))%36)+1,1)+
                            substring(x,(abs(checksum(newid()))%36)+1,1)
From        LookupString  
Cross Join  Numbers
Where       N <= 100