SQLite equivalent to ISNULL(), NVL(), IFNULL() or

2020-01-27 02:16发布

I'd like to avoid having many checks like the following in my code:

myObj.someStringField = rdr.IsDBNull(someOrdinal) 
                            ? string.Empty 
                            : rdr.GetString(someOrdinal);

I figured I could just have my query take care of the nulls by doing something like this:

SELECT myField1, [isnull](myField1, '') 
FROM myTable1
WHERE myField1 = someCondition

I'm using SQLite though and it doesn't seem to recognize the isnull function. I've also tried some equivalent ones recognized in other databases (NVL(), IFNULL() and COALESCE()), but SQLite doesn't seem to recognize any of them.

Does anyone have any suggestions or know of a better way to do this. Unfortunately the database doesn't have default values for all fields. Plus, I need to use some LEFT JOIN clauses in some cases, where some of the fields returned will be null because the matching record in the LEFT JOIN table will not exist.

6条回答
走好不送
2楼-- · 2020-01-27 02:25

For the equivalent of NVL() and ISNULL() use:

IFNULL(column, altValue)

column : The column you are evaluating.

altValue : The value you want to return if 'column' is null.

Example:

SELECT IFNULL(middle_name, 'N/A') FROM person;

*Note: The COALESCE() function works the same as it does for other databases.

Sources:

查看更多
手持菜刀,她持情操
3楼-- · 2020-01-27 02:42

Try this

ifnull(X,Y)  

e.g

select ifnull(InfoDetail,'') InfoDetail; -- this will replace null with ''
select ifnull(NULL,'THIS IS NULL');-- More clearly....

The ifnull() function returns a copy of its first non-NULL argument, or NULL if both arguments are NULL. Ifnull() must have exactly 2 arguments. The ifnull() function is equivalent to coalesce() with two arguments.

查看更多
孤傲高冷的网名
4楼-- · 2020-01-27 02:43

If there is not ISNULL() method, you can use this expression instead:

CASE WHEN fieldname IS NULL THEN 0 ELSE fieldname END

This works the same as ISNULL(fieldname, 0).

查看更多
小情绪 Triste *
5楼-- · 2020-01-27 02:43

Use IS NULL or IS NOT NULL in WHERE-clause instead of ISNULL() method:

SELECT myField1
FROM myTable1
WHERE myField1 IS NOT NULL
查看更多
放荡不羁爱自由
6楼-- · 2020-01-27 02:46

You can easily define such function and use it then:

ifnull <- function(x,y) {
  if(is.na(x)==TRUE) 
    return (y)
  else 
    return (x);
}

or same minified version:

ifnull <- function(x,y) {if(is.na(x)==TRUE) return (y) else return (x);}
查看更多
啃猪蹄的小仙女
7楼-- · 2020-01-27 02:51

IFNULL, see here: http://www.sqlite.org/lang_corefunc.html#ifnull

no brackets around the function

查看更多
登录 后发表回答