What is the best way to create and populate a numbers table?

后端 未结 11 2521
悲&欢浪女
悲&欢浪女 2020-11-21 13:28

I\'ve seen many different ways to create and populate a numbers table. However, what is the best way to create and populate one? With \"best\" being defined from most to l

11条回答
  •  不思量自难忘°
    2020-11-21 13:47

    If you're just doing this in either SQL Server Management Studio or sqlcmd.exe, you can use the fact that the batch separator allows you to repeat the batch:

    CREATE TABLE Number (N INT IDENTITY(1,1) PRIMARY KEY NOT NULL);
    GO
    
    INSERT INTO Number DEFAULT VALUES;
    GO 100000
    

    This will insert 100000 records into the Numbers table using the default value of the next identity.

    It's slow. It compares to METHOD 1 in @KM.'s answer, which is the slowest of the examples. However, it's about as code light as it gets. You could speed it up somewhat by adding the primary key constraint after the insert batch.

提交回复
热议问题