Smartkid's binary life

博客园 首页 联系 订阅 管理
  10 随笔 :: 1 文章 :: 24 评论 :: 25127 阅读

 

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.Numberas 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

用此方法插入数据,要比利用循环快很多倍。

posted on   Smartkid  阅读(1278)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示