tags:

views:

34

answers:

3

Hi, I am pretty new in TSQL, 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? thanks -- 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
A: 

The script is fine, but insertion of 5000 rows one by one will not be fast.

spbfox
+3  A: 

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

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;
Paul McLoughlin
I probably should have said in the original answer, but the reason for using NEWID() rather than RAND() is that RAND() would be executed once giving same value for each row, but NEWID() is evaluated for each row.
Paul McLoughlin
Thanks Paul, for sure I will test your script, thanks once again
GIbboK