WITH Digits AS (
SELECT 0 as Number
UNION SELECT 1
UNION SELECT 2
UNION SELECT 3
UNION SELECT 4
UNION SELECT 5
UNION SELECT 6
UNION SELECT 7
UNION SELECT 8
UNION SELECT 9
)
SELECT
(d5.Number * 100000)
+ (d4.Number * 10000)
+ (d3.Number * 1000)
+ (d2.Number * 100)
+ (d1.Number * 10)
+ d0.Number as Number
FROM
Digits AS d0
, Digits AS d1
, Digits AS d2
, Digits AS d3
, Digits AS d4
, Digits AS d5
在SQLServer 2005中,这个SQL返回一个包含1000000条记录的结果集,从0到999999。
这条语句利用了SQL2005的新功能:CTE (Common Table Expression)
如果当前的数据库是SQL 2000或其他不支持CTE的数据库,则可以将WITH部分的SQL定义为一个视图。
CREATE VIEW .[Digits] AS
SELECT 0 AS Number
UNION SELECT 1
UNION SELECT 2
UNION SELECT 3
UNION SELECT 4
UNION SELECT 5
UNION SELECT 6
UNION SELECT 7
UNION SELECT 8
UNION SELECT 9;
CREATE VIEW [MillionNumbers] AS
SELECT
SELECT (d5.Number * 100000)
+ (d4.Number * 10000)
+ (d3.Number * 1000)
+ (d2.Number * 100)
+ (d1.Number * 10)
+ d0.Number) as Number
FROM
Digits AS d0
, Digits AS d1
, Digits AS d2
, Digits AS d3
, Digits AS d4
, Digits AS d5;
我们可以用这个方法来生成大批量的测试数据。如:
INSERT INTO MyTest (RecordId, RecordIndex)
SELECT newid(), Number FROM MillionNumbers
用此方法插入数据,要比利用循环快很多倍。
零七网部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与零七网进行文章共享合作。