如果使用SQL,表记录计数= 1,我想总是保留一条记录

时间:2009-10-18 15:12:13

标签: sql sql-delete

我可以删除带有这个SQL子句的记录,

DELETE FROM TABLE WHERE ID = 2

如果表计数= 1,即使“ID = 2”,我也需要留下一条记录。我怎么能这样做?

3 个答案:

答案 0 :(得分:4)

添加WHERE子句以确保有多行:

DELETE FROM TABLE 
WHERE ID = 2
AND (SELECT COUNT(*) FROM TABLE) > 1

答案 1 :(得分:1)

未经测试,但有些内容可能会有效吗?

DELETE FROM TABLE WHERE ID = 2 LIMIT (SELECT COUNT(*)-1 FROM TABLE WHERE ID=2);

也许添加if语句以确保计数高于1.

答案 2 :(得分:1)

简单的方法是禁止任何清空表格的删除

CREATE TRIGGER TRG_MyTable_D FOR DELETE
AS
IF NOT EXISTS (SELECT * FROM MyTable)
    ROLLBACK TRAN
GO

更复杂的是,如果你执行这个多行删除会清空表怎么办?

DELETE FROM TABLE WHERE ID BETWEEN 2 AND 5

所以,从你刚刚删除的内容中随机重新填充

CREATE TRIGGER TRG_MyTable_D FOR DELETE
AS
IF NOT EXISTS (SELECT * FROM MyTable)
    INSERT mytable (col2, col2, ..., coln)
    SELECT TOP 1 col2, col2, ..., coln FROM INSERTED --ORDER BY ??

GO

但是,要求有点危险和模糊。在英语中,好的,“表中至少有一行”,但实际上“哪一行?”