2014-12-04 62 views
-3

假设有一张表,其中包含卷号1至10的学生记录。如果我们在卷号4 &处删除记录5。是否可以在4 & 5处输入新记录?任何人都可以请帮忙。标识栏的自定义值

+1

如果在INSERT查询中指定卷号,它将使用它。 – Barmar 2014-12-04 10:43:24

+1

取决于表的架构,并可能执行代码的用户拥有的权限(可能需要能够设置IDENTITY_INSERT) – 2014-12-04 10:43:25

+1

@Barmar:不一定。例如,如果卷号的列也是标识列,并且“IDENTITY_INSERT”选项关闭,则无法插入具有特定卷号(4,5)的记录。就像Rowland Shaw所说的那样,这取决于模式。 – stakx 2014-12-04 10:51:23

回答

0

是的,您可以使用SET IDENTITY_INSERT这样做,因为对于StudentRollID列,指定IDENTITY(1, 1)。这意味着,随着每行被插入到表中,SQL Server会自动将此值从1开始递增1.

-- 1 - Retrieve all of the data 
-- from the dbo.Student table 
SELECT * 
FROM dbo.Student; 
GO 

-- 2 - Delete a single record 
DELETE 
FROM dbo.Student 
WHERE StudentRollID = 4; 
GO 

-- 3 - Verify the record was deleted 
SELECT * 
FROM dbo.Student; 
GO 

-- 4 - Insert the deleted record 
-- Insert fails 
INSERT INTO [dbo].[Student] 
([StudentRollID] 
,[FirstName] 
,[LastName] 
,[CreateDate]) 
VALUES 
(4 
,'Bar' 
,'Foo' 
,'2014-12-04'); 
GO 

-- 5 - Insert the deleted record 
-- Insert succeeds 
SET IDENTITY_INSERT [dbo].[Student] ON 
INSERT INTO [dbo].[Student] 
([StudentRollID] 
,[FirstName] 
,[LastName] 
,[CreateDate]) 
VALUES 
(4 
,'Bar' 
,'Foo' 
,'2014-12-04'); 
SET IDENTITY_INSERT [dbo].[Student] OFF 
GO 

-- 6 - Verify the data 
SELECT * 
FROM dbo.Student; 
GO