Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating test load for self-referencing table
    primarykey
    data
    text
    <p>I have to do some SQL Server 2008 R2 performance testing and it would be very convenient to do it using only SSMS and SQL Server, without additional application support.</p> <p>One of the tests I have to do is querying a self-referencing table (tree-like structure) with unknown content. So, for a start I would have to load something like 100K - 1M randomly parent-child-related rows into this table.</p> <pre><code>CREATE TABLE Test2 ( ID int IDENTITY(1,1) PRIMARY KEY CLUSTERED NOT NULL, ParentID int NULL REFERENCES Test2 (ID)) </code></pre> <p>I am currently trying with SSMS and this script to load 10K rows into the table:</p> <pre><code>SET NOCOUNT ON INSERT INTO Test2 (ParentID) VALUES (NULL) DECLARE @n int = 0 ;WHILE(1=1) BEGIN --PRINT @n INSERT INTO Test2 (ParentID) SELECT TOP 1 ID FROM Test2 ORDER BY NEWID() SET @n = @n + 1 IF(@n &gt;= 9999) BREAK END SET NOCOUNT OFF </code></pre> <p>My problem is that it runs something like 2m 45s on my laptop. You can imagine how long it would take to load 100K or even 1M records this way.</p> <p>I would like to have a faster way to load this random tree-like structure into database table using TSQL?</p> <p><strong>EDIT:</strong> After Mitch Wheat's suggestion, I replaced</p> <pre><code>SELECT TOP 1 ID FROM Test2 ORDER BY NEWID() </code></pre> <p>with</p> <pre><code>SELECT TOP 1 ID FROM Test2 WHERE ID &gt;= RAND(CHECKSUM(NEWID())) * (SELECT MAX(ID) FROM Test2) </code></pre> <p>Regarding random row selection, results really look uniformly distributed. Execution time falls from 160s to 5s (!) -> this enables me to insert 100K records in ~60s. However, inserting 1M records using my RBAR script is still very slow and I'm still searching for possible set-based expression to fill my table. If it exists.</p> <p>Now, after ~10mins of filling random data I have 1M rows. It is slow but acceptable. However, to copy this data to another table using batch insert it takes &lt;10s.</p> <pre><code>SELECT * INTO Test3 FROM Test2 </code></pre> <p>So, I believe some form of batch insert could speed up the process.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload