SQL服务器 - 删除多列具有null值或零值的行

时间:2011-02-10 21:29:16

标签: sql sql-server-2008

我是一个DB新手,我正在努力解决这个问题。我有一个包含以下列的现有表:

Showroom, Salesperson, Time1, Time2, Time3, Dte

我正在尝试删除表中所有3个时间列中包含null值或零值的行。我尝试了以下方法:

DELETE FROM myTable 
WHERE EXISTS(
              SELECT * 
              FROM myTable 
              WHERE (Time1 IS NULL OR Time1 = 0) 
                AND (Time2 IS NULL OR Time2 = 0) 
                AND (Time3 IS NULL OR Time3 = 0)
            )

幸运的是,我正在研究数据库的测试版本,因为我删除了所有数据。真的很感激任何帮助。

7 个答案:

答案 0 :(得分:19)

查询的格式应如下:

DELETE 
FROM myTable 
WHERE (Time1 IS NULL OR Time1 = 0) 
AND (Time2 IS NULL OR Time2 = 0) 
AND (Time3 IS NULL OR Time3 = 0)

在执行DELETE语句时,我认为 总是最好首先创建SELECT语句,然后更改它。

SELECT * --If this returns the correct records, simply change to DELETE
FROM myTable 
WHERE (Time1 IS NULL OR Time1 = 0) 
AND (Time2 IS NULL OR Time2 = 0) 
AND (Time3 IS NULL OR Time3 = 0)

答案 1 :(得分:3)

你想要的只是;

DELETE myTable
WHERE
  (Time1 IS NULL OR Time1 = 0)
  AND (Time2 IS NULL OR Time2 = 0)
  AND (Time3 IS NULL OR Time3 = 0)

答案 2 :(得分:1)

EXISTS是多余的(与FROM一样 - DELETE s不需要它:

DELETE myTable 
WHERE ((Time1 IS NULL OR Time1 = 0) 
  AND (Time2 IS NULL OR Time2 = 0) 
  AND (Time3 IS NULL OR Time3 = 0))

答案 3 :(得分:1)

请改为尝试:

DELETE 
FROM myTable 
WHERE 
  (Time1 IS NULL OR Time1 = 0) AND 
  (Time2 IS NULL OR Time2 = 0) AND 
  (Time3 IS NULL OR Time3 = 0)

删除所有记录的原因是因为EXISTS结果为真,只要存在单个记录为NULL或0为所有三列。由于delete语句的WHERE子句无法识别要删除的记录,因此它与DELETE FROM myTable WHERE 1=1基本相同

答案 4 :(得分:0)

DELETE myTable WHERE 
(ISNULL(Time1,0) = 0) AND (ISNULL(Time2,0) = 0) AND (ISNULL(Time3,0) = 0)

答案 5 :(得分:0)

这是删除空白行和NULL的查询

DELETE FROM table_name WHERE COL_NAME='' OR COL_NAME IS NULL;

答案 6 :(得分:0)

您可以做的是在MS中自动创建一个选择查询,然后用[查找和替换符号(ISNULL([,用]替换符号],0) = 0)。 并为所有数字字段AND获取(ISNULL(Time1,0) = 0) AND条件。