我正在尝试删除表的最后一行,我有一个程序,它有效,但在我删除行之前,我需要将其移动到另一个表,工作类似于备份,是有没有办法在相同的过程中进行插入和删除,或者需要创建两个不同的过程?
Insert into T_CLIC_DELETE _LOG
values (iClic,iStatus ,dtDateCreated,iEDV)
From T_STATUS_CLIC
WHERE iClic = @iClic and dtDateCreated = (select max (dtDateCreated) FROM T_STATUS_CLIC where iclic = @iClic );
并且需要删除部分之后:
DELETE From T_STATUS_CLIC
WHERE iClic = @iClic and dtDateCreated = (select max (dtDateCreated)
FROM T_STATUS_CLIC where iclic = @iClic );
答案 0 :(得分:2)
是的,你可以用同样的程序来做。
只要T_CLIC_DELETE_LOG
满足OUTPUT
子句目标表的要求,您就可以在一个语句中完成所有操作。
;WITH T
AS (SELECT TOP 1 *
FROM T_STATUS_CLIC
WHERE iClic = @iClic
ORDER BY dtDateCreated DESC)
DELETE T
OUTPUT deleted.iClic,
deleted.iStatus,
deleted.dtDateCreated,
deleted.iEDV
INTO T_CLIC_DELETE_LOG
(如果TOP 1 WITH TIES
符合条件,则应删除所有行,您可以使用MAX(dtDateCreated)
答案 1 :(得分:1)
WITH t AS
(
SELECT TOP 1
*
FROM t_status_clic
WHERE iClic = @iClic
ORDER BY
dtDateCreated DESC
)
INSERT
INTO t_clic_delete_log
SELECT *
FROM (
DELETE
FROM t
OUTPUT DELETED.*
) q