开发者

SQL server - delete rows where multiple columns have either null or zero value

开发者 https://www.devze.com 2023-02-09 16:20 出处:网络
I\'m a DB newbie, and am struggling with this.I have an existing table with the followi开发者_StackOverflow社区ng columns:

I'm a DB newbie, and am struggling with this. I have an existing table with the followi开发者_StackOverflow社区ng columns:

Showroom, Salesperson, Time1, Time2, Time3, Dte

I'm trying to delete all rows within the table that have either null or zero values in all 3 time columns. I tried the following:

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)
            )

Thankfully I'm working on a test version of the database, as I wiped out all of the data. Any help would truly be appreciated.


The query should be formatted like this:

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

When doing DELETE statements I think it is always best to first create your SELECT statement, and then change it.

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)


What you want is just;

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


The EXISTS is superfluous (as is the FROM - it isn't needed for DELETEs):

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


Try this instead:

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

The reason all of your records are being deleted is because the EXISTS result is true as long as there exists a single record that has NULL or 0 for all three columns. Since your WHERE clause of the delete statement doesn't identify which records to delete, it is essentially the same as DELETE FROM myTable WHERE 1=1


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


Here is the query to delete blank rows as well as NULL

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


What you can do is to create a select query in MS automatically, then find and replace symbols [ with (ISNULL([, ] with ],0) = 0). and to get AND condition for all numeric fields (ISNULL(Time1,0) = 0) AND.

0

精彩评论

暂无评论...
验证码 换一张
取 消