标识列的自定义值

时间:2014-12-04 10:38:05

标签: sql-server

假设有一个表格,其中包含1号到10号卷的学生记录。如果我们删除4号和5号卷的记录。是否可以在4& 5输入新记录?任何人都可以帮忙。

1 个答案:

答案 0 :(得分:1)

是的,您可以使用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