如果一列为空,如何删除整行

时间:2013-12-18 16:34:21

标签: sql

说我有下表:

Tree     Park      Slide       
1           1        1
1           1        1
                     1
1                    1

我将使用哪种代码来删除具有空列的行,以便我得到以下结果

 Tree     Park      Slide       
    1           1        1
    1           1        1

我是sql的新手,并想知道如何编写此代码的一些提示。我会使用一个案例陈述

Case
WHEN Tree IS NULL OR Park IS NULL
--Then what would I say to remove the row

6 个答案:

答案 0 :(得分:7)

使用DELETE删除行,并在IS NULL子句中使用WHERE进行检查。

DELETE FROM dbo.TableName
WHERE Tree IS NULL OR Park IS NULL OR Slide IS NULL

如果您还想删除其中一列不为空但为空文本(如果它是varchar列)的行:

DELETE FROM dbo.TableName
WHERE (Tree IS NULL OR Tree = '') 
 OR   (Park IS NULL OR Park = '') 
 OR   (Slide IS NULL OR Slide = '') 

答案 1 :(得分:2)

如果您的意思是实际删除,那么只需将其放入WHERE

DELETE FROM {table}
WHERE Tree IS NULL 
   OR Park IS NULL
   OR Slide IS NULL

或者利用{null} + n = {null}而只是做的事实:

DELETE FROM {table}
WHERE (Tree+Park+Slide) IS NULL

但我会肯定添加评论来解释为什么有效。

如果您的意思是SELECT结果中排除,那么您可以使用:

SELECT *
FROM {table}
WHERE Tree IS NOT NULL 
  AND Park IS NOT NULL
  AND Slide IS NOT NULL

答案 2 :(得分:0)

不需要case语句,只需要where子句:

SELECT *
FROM Table
WHERE Tree IS NOT NULL
AND Park IS NOT NULL
AND Slide IS NOT NULL

注意 - 阅读注释 - 这不会从数据库中删除,只是过滤选择的输出。 Tim Schmelter的答案对于删除是正确的。

答案 3 :(得分:0)

是的,像DELETE FROM TABLE WHERE Tree IS NULL or Park IS NULL or Slide IS NULL之类的东西会起作用。

答案 4 :(得分:0)

您可以尝试使用这样的delete: -

DELETE FROM tablename
WHERE Tree IS NULL 
   OR Park IS NULL
   OR Slide IS NULL

答案 5 :(得分:0)

DELETE FROM dbo.TableName
WHERE (Tree+Park) IS NULL 

这是因为

  

NULL + NonNullValue = NULL


  

NULL NULL + = NULL

(显然)

更简单的方法是:

DELETE FROM TABLE
WHERE Tree is NULL OR Park is NULL