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
用此方法插入數據,要比利用循環快很多倍。