我想使用sqlcommand
从相关表(具有相同外键ID的记录)中删除2条记录。
是否有任何类似SCOPE_IDENTITY
的方法返回最后一个ID已被删除?
我不想使用ON DELETE CASCADE
约束。有什么想法吗?
感谢。
答案 0 :(得分:1)
如何在SQL Server中获取已删除的标识号:
让我们有一张员工表,其中一些员工记录与每位员工的唯一身份号码一起保存 现在,假设由于某些原因从Employee表中删除了一些记录,现在我们想要从Employee表中删除所有已删除的记录,现在可能无法从表中删除记录,但我们可以获取唯一标识列表使用查询从Employee表中删除记录。
-- Create Employee Table
Create Table EMPLOYEE( ID int,EmpID int,EmpName varchar(50))
-- Insert Sample data to the Employee table
INSERT INTO EMPLOYEE VALUES ( 1, 1, 'Aasish')
INSERT INTO EMPLOYEE VALUES ( 2, 1, 'Anita');
INSERT INTO EMPLOYEE VALUES ( 3, 1, 'Kabita');
INSERT INTO EMPLOYEE VALUES ( 4, 2, 'Raj');
INSERT INTO EMPLOYEE VALUES ( 5, 2, 'Babita');
INSERT INTO EMPLOYEE VALUES ( 6, 2, 'Geet');
INSERT INTO EMPLOYEE VALUES ( 7, 2, 'Krishh');
INSERT INTO EMPLOYEE VALUES ( 8, 3, 'Kabir');
INSERT INTO EMPLOYEE VALUES ( 9, 3, 'Rasmita');
INSERT INTO EMPLOYEE VALUES ( 10, 3, 'Sam');
-- Delete data from the Employee table
DELETE EMPLOYEE WHERE ID IN(1,10,12);
--- Retrive the Employee table data after deleting the records
SELECT ID FROM EMPLOYEE
--- Retrive the deleted unique identity numbers from the Employee table
WITH Missing (missnum, maxid)
AS
(
SELECT 1 AS missnum, (select max(id) from EMPLOYEE) UNION ALL SELECT missnum + 1, maxid FROM Missing
WHERE missnum < maxid
)
SELECT missnum FROM Missing
LEFT OUTER JOIN EMPLOYEE e on e.id = Missing.missnum
WHERE e.id is NULL OPTION (MAXRECURSION 0);