| 有一种东西叫 Tally table: 
 --Declare TestTable Variable
 declare @t table (FieldA int, FieldB varchar(50), FieldC varchar(50))
 insert into @t
 values
 (3, 'John', 'Smith'),
 (2, 'John', 'Smith'),
 (2, 'Jack', 'London')
 
 --Genera Tally table (for SQL 2008+)
 ;WITH Tally (n) AS
 (
 -- 1000 rows (10 x 10 x 10)
 SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
 FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
 CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
 CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)
 )
 SELECT
 --t.FieldA,
 l.n,
 t.FieldB,
 t.FieldC
 FROM @t t
 LEFT JOIN Tally l ON t.FieldA>=l.n
 --ORDER by t.FieldA, t.FieldB, t.FieldC, l.n desc /* uncomment order clause in dev only */
 
 
 T-SQL用set based operation是最快的。在使用loop和cte之前,先想想能不能用set based operation实现。
 
 顺带一提,我公司招Senior Microsoft BI Developer, SSAS Tabular, SSIS, SSRS, Spark on HDInsight, Azure IaaS, PaaS, Power Shell. 如有兴趣,发我邮件: george.qiao@staples.com.au
 |