Mega Code Archive

 
Categories / MSSQL Tutorial / Query
 

Deal with divided by 0

3> 4> CREATE TABLE MyTable( 5> col1 int NOT NULL, 6> col2 int NOT NULL) 7> INSERT INTO MyTable VALUES(1, 1) 8> INSERT INTO MyTable VALUES(1, 0) 9> INSERT INTO MyTable VALUES(-1, 1) 10> 11> 12> SELECT * FROM MyTable WHERE (col1 / col2 > 0) 13> GO (1 rows affected) (1 rows affected) (1 rows affected) col1        col2 ----------- ----------- Msg 8134, Level 16, State 1, Server BCE67B1242DE45A\SQLEXPRESS, Line 12 Divide by zero error encountered.           1           1 Msg 8134, Level 16, State 1, Server BCE67B1242DE45A\SQLEXPRESS, Line 12 Divide by zero error encountered. 1> SELECT * FROM MyTable WHERE (col2 <> 0) AND (col1 / col2 > 0) 2> GO col1        col2 ----------- -----------           1           1 (1 rows affected) 1> SELECT * FROM MyTable WHERE (col1 / col2 > 0) AND (col2 <> 0) 2> GO col1        col2 ----------- -----------           1           1 (1 rows affected) 1> SELECT * FROM MyTable WHERE 2>   CASE 3>     WHEN col2 = 0        THEN 0 4>     WHEN col1 / col2 > 0 THEN 1 5>     ELSE 0 6>   END = 1 7> GO col1        col2 ----------- -----------           1           1 (1 rows affected) 1> 2> drop table MyTable 3> GO