如何填充仅包含标识列的表?

时间:2018-10-07 16:40:39

标签: sql-server

请参阅下表

CREATE TABLE [dbo].[Numbers]
(
    [Id] [INT] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]

如何填充?

如果我添加一列(例如text nchar(20)),则可以使用以下内容填充它:

insert into numbers (text) values ('')

但是如果身份之外没有其他列,我该怎么办?

insert into numbers ( ) values ( )

这会引发错误

  

')'附近的语法不正确。

我想用它来查找丢失的序列号问题。

2 个答案:

答案 0 :(得分:3)

指定DEFAULT VALUES

INSERT INTO dbo.Numbers DEFAULT VALUES;

答案 1 :(得分:1)

或者甚至可以使用SET IDENTITY_INSERT

SET IDENTITY_INSERT YourTable ON;  
GO 
INSERT INTO YourTable (IdentityColumn) VALUES
(1),
(2),
(3);
GO
SET IDENTITY_INSERT YourTable OFF;

示例:

CREATE TABLE [dbo].[Numbers](
    [Id] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY];

DECLARE @Start INT=1;
DECLARE @End INT=100;

SET IDENTITY_INSERT [dbo].[Numbers] ON;
WITH Gen AS (
    SELECT @Start AS Num
    UNION ALL
    SELECT Num + 1 FROM Gen WHERE Num + 1 <= @End
)
INSERT INTO [dbo].[Numbers] (Id)
SELECT Num 
FROM Gen
OPTION (maxrecursion 100);

SET IDENTITY_INSERT [dbo].[Numbers] OFF;

SELECT *
FROM [dbo].[Numbers];