I agree with Flo... if, for some reason, you cannot use IDENTITY and you're stuck with SQL Server 2000 or less which prevents the use of ROW_NUMBER and the like, then the "quirky" update Flo used is absolutely the fastest method available. That method is good for a lot of things like running totals, ranking, and some incredibly odd groupings.
There are, however, some fairly strict rules to using it if you actually want to control what it does. Those rules and some of the methods are covered by an article (currently being rewritten) that will reappear at the following URL sometime in the next month or so.
http://www.sqlservercentral.com/articles/Advanced+Querying/61716/
If I could also make a wee bit of a suggestion... if you want to build a test table for something, there's simply no reason to go through the complexity of building a While Loop nor the wait while it works... not even in SQL Server 2000. To wit, the While Loop in the article takes a little over 7 seconds to build the test table. Using a little set-based programming and a little knowledge of the functions available in SQL Server, it can be done with much less complexity and it executes in about 250 milli-seconds.
[font="Courier New"]--===== Conditionally drop the test table for test reruns
IF OBJECT_ID('tempdb..#my_tab') IS NOT NULL
DROP TABLE #my_tab
--===== Build the test table and populate it with data on the fly
SET STATISTICS TIME ON
SELECT TOP 100000
CAST(NULL AS INT) AS ID,
DATEADD(mi,-ABS(CHECKSUM(NEWID())%100000),GETDATE()) AS Any_Date
INTO #My_Tab
FROM Master.dbo.SysColumns t1 CROSS JOIN Master.dbo.SysColumns t2
SET STATISTICS TIME OFF[/font]
I mention this because, frequently, testing against larger numbers of rows is ensential to ensuring performance in the face of scalability. To test against a million rows, the While Loop takes a whopping big 80+ seconds on my box. Worse yet, it also practices you in RBAR thinking instead of set based thinking. The simple set based solution only takes 2.319 seconds to produce the same million row test table. Folks are much more likely to test repeatedly if they can setup test data that quickly.
Heh... yeah... I know... Someone once told me that this was easy for me but not for them. That's my point... if they keep practicing RBAR methods instead of learning how to do the very high speed set based methods, it will never be easy for them. 😛
Anyway... good tip, Flo. Keep 'em coming. 🙂
--Jeff Moden
Change is inevitable... Change for the better is not.