Technical Article

Using GO Repeat To Fill Tally Table

,

This script can be used to fill a primary key column quickly without using a traditional loop or cursor. The interesting part is the "GO n" section which will repeat code within the batch "n" number of times. Be sure to create the TinyTally table first.

-- tally table used for parsing smallish columns dbo.TinyTally(N tinyint IDENTITY PRIMARY KEY);
SET IDENTITY_INSERT dbo.TinyTally ON;
GO
-- Prime the table first
INSERT dbo.TinyTally(N) VALUES(IDENT_CURRENT('dbo.TinyTally'));
GO
INSERT dbo.TinyTally(N) VALUES(IDENT_CURRENT('dbo.TinyTally')+1);
GO 254 -- Really cool tidbit I picked up from SQL Saturday #40 (will now repeat batch 254 times!)
SET IDENTITY_INSERT dbo.TinyTally OFF;
GO
SELECT * FROM dbo.TinyTally;
GO

Rate

3.83 (6)

You rated this post out of 5. Change rating

Share

Share

Rate

3.83 (6)

You rated this post out of 5. Change rating