使用 WHILE 创建虚拟数据

Create dummy data with WHILE(使用 WHILE 创建虚拟数据)
本文介绍了使用 WHILE 创建虚拟数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我尝试使用 WHILE 在我的表中插入一些虚拟数据,但它运行起来真的很慢.

I try to insert some dummy data inside my table using a WHILE, but it run really really slow.

我在想可能是我写的代码不正确,请您看一下并确认一下吗?

I was thinking maybe I am writing not properly the code, could yo please have a look and confirm it?

-- Insert dummy data

DECLARE
    @i          int,
    @Content    int;
SET @i = 5001;

WHILE @i > 5000 AND @i < 10000
BEGIN
    SET @Content = ROUND(((10000-5000)*RAND()+5000),0)
    INSERT INTO dbo.CmsImagesContents
    (ContentId, Title, AltTag, Caption)
    VALUES
    (@Content,'Test Title', 'Test AltTag', 'Test Caption');
    SET @i = @i + 1;
END

推荐答案

与在循环中执行 4999 条单独的插入语句相比,如果对所有 4999 行执行一次插入,您将获得更好的性能.因此,如果您有一个包含 4999 行的表 #T,您只需调用以下代码:

Rather than doing 4999 separate insert statements in a loop, you'll get much better performance if you do a single insert of all 4999 rows. So, if you have a table #T containing 4999 rows you would simply call the following:

INSERT INTO DBO.CmsImagesContents(ContentId, Title, AltTag, Caption)    
SELECT (ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) % 5000) + 5000 AS ContentID, 
        'Test Title' AS Title, 'Test AltTag' AS AltTag, 'Test Caption'  AS Caption
FROM #T1

如果您首先需要创建这样一个包含 4999 行的表,那么以下 SQL 将适合您:

If you need to create such a table of 4999 rows in the first place then the following SQL would work for you:

CREATE TABLE #T1
(
    N INT NOT NULL PRIMARY key
);

WITH L0 AS (SELECT 1 AS N UNION ALL SELECT 1), 
    L1 AS (SELECT A.N FROM L0 AS A CROSS JOIN L0 AS B),
    L2 AS (SELECT A.N FROM L1 AS A CROSS JOIN L1 AS B),
    L3 AS (SELECT A.N FROM L2 AS A CROSS JOIN L2 AS B),
    L4 AS (SELECT A.N FROM L3 AS A CROSS JOIN L3 AS B),
    Nums AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS n FROM L4)

INSERT INTO #T1( N )
SELECT N
FROM Nums
WHERE n < 10000 AND n>5000;

这篇关于使用 WHILE 创建虚拟数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Number of working days between two dates(两个日期之间的工作日数)
How do I use dateadd to get the first day of last year?(如何使用 dateadd 获取去年的第一天?)
SQL- Count occurrences of a specific word within all stored procedures(SQL- 计算所有存储过程中特定单词的出现次数)
SQL query to make a column of numbers a string(使一列数字成为字符串的 SQL 查询)
T-SQL: Best way to replace NULL with most recent non-null value?(T-SQL:用最新的非空值替换 NULL 的最佳方法?)
Count days in date range with set of exclusions which may overlap(使用一组可能重叠的排除项计算日期范围内的天数)