获取 SQL 中的选定值

Get Selected values in SQL

我想比较日期时间并删除超过 72 小时的行。然后我想更新另一个 table 布尔值 "HasClone"。如何从第一个选择中获取整数(ID)到另一个?请参阅下面的代码:

 SELECT Allocation_plan_details_Clone.Allocation_plan_id AS ID
         FROM Allocation_plan_details_Clone
         WHERE DATEDIFF(hour, start_date, GETDATE()) > 72
         UPDATE Allocation_plan
         SET HasClone = 0
         WHERE allocation_plan_id = <INSERT CODE HERE!>
         DELETE FROM Allocation_plan_details_Clone
         WHERE DATEDIFF(hour, start_date, GETDATE()) > 72

所以在 "INSERT CODE HERE!" 我想插入我刚从 Allocation_plan_details_Clone

获得的 ID

如果我没看错你的问题,我想你想要的是:

UPDATE Allocation_plan
SET HasClone = 0
WHERE allocation_plan_id IN (
    SELECT Allocation_plan_details_Clone.Allocation_plan_id
    FROM Allocation_plan_details_Clone
    WHERE DATEDIFF(hour, start_date, GETDATE()) > 72
)

如果我没理解错的话,你可以创建一个临时文件 table(驻留在该数据库连接上并在你断开连接后立即删除自身。

它会是这样的:

SELECT Allocation_plan_details_Clone.Allocation_plan_id AS ID INTO #temp_table
         FROM Allocation_plan_details_Clone
         WHERE DATEDIFF(hour, start_date, GETDATE()) > 72
         UPDATE Allocation_plan
         SET HasClone = 0
         WHERE allocation_plan_id = <INSERT CODE HERE!>
         DELETE FROM Allocation_plan_details_Clone
         WHERE DATEDIFF(hour, start_date, GETDATE()) > 72
;

然后你可以用这个温度table做任何你想做的事,例如:

delete
from other_table
where id in (select id from #temp_table)
;

注意:不确定您 运行 使用的 DBMS,但是 MSSQL 有一个引用临时 table 的主题标签。 Postgres 我认为您不需要这样做并且不确定其他 DBMS。

你可以使用temptable来保存你想要的IDS,就是这样

SELECT Allocation_plan_details_Clone.Allocation_plan_id AS ID
into #TempTable
FROM Allocation_plan_details_Clone
WHERE DATEDIFF(hour, start_date, GETDATE()) > 72

UPDATE a
SET HasClone = 0
WHERE allocation_plan_id in (select ID from #TempTable)

DELETE FROM Allocation_plan_details_Clone
WHERE DATEDIFF(hour, start_date, GETDATE()) > 72

这个答案是在删除行时将 Allocation_plan_id 放入 table 变量。

事务确保数据不会在不更新 Allocation_plan table 的情况下被删除。

我重写了您的 WHERE 语句以提高性能。

begin transaction t

DECLARE @deleted table(Allocation_plan_id int)

DELETE Allocation_plan_details_Clone
OUTPUT deleted.Allocation_plan_id
INTO @deleted
FROM Allocation_plan_details_Clone
WHERE start_date < dateadd(hour, -72, GETDATE())

UPDATE Allocation_plan
SET HasClone = 0
FROM Allocation_plan
JOIN
@deleted d
ON d.Allocation_plan_id = Allocation_plan.Allocation_plan_id

commit transaction t;