Sql server 标识列的自定义值
假设有一个表包含从第1卷到第10卷的学生记录。如果我们删除第4卷和第5卷的记录。是否可以在4点和5点输入新记录?任何人都可以提供帮助。是的,您可以使用指定了Sql server 标识列的自定义值,sql-server,Sql Server,假设有一个表包含从第1卷到第10卷的学生记录。如果我们删除第4卷和第5卷的记录。是否可以在4点和5点输入新记录?任何人都可以提供帮助。是的,您可以使用指定了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
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
如果您在
INSERT
查询中指定卷号,它将使用它。这取决于表的架构,可能还取决于执行代码的用户拥有的权限(可能需要能够设置IDENTITY\u INSERT)@Barmar:不一定。例如,如果卷号列也是标识列,并且identity\u INSERT
选项已关闭,则无法插入具有特定卷号(4、5)的记录。正如Rowland Shaw所说,这取决于模式。@barmar但如果我们不知道数据库中哪个Entry是空的,那么?我希望Entry在那个空白位置,为什么需要这样做?重用IDs通常是个坏主意。