SQLite 等效于 ISNULL()、 NVL()、 IFNULL()或 COALESCE()

在我的代码中,我希望避免像下面这样的许多检查:

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

我想我可以通过这样的方式让我的查询处理 null:

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

但是我使用的是 SQLite,它似乎不能识别 isnull函数。我还尝试了在其他数据库(NVL()IFNULL()COALESCE())中识别的一些类似的数据库,但 SQLite 似乎不能识别它们中的任何一个。

是否有人有任何建议或知道一个更好的方法来做到这一点。遗憾的是,数据库没有所有字段的默认值。另外,在某些情况下,我需要使用一些 LEFT JOIN子句,其中一些返回的字段将为空,因为 LEFT JOIN表中的匹配记录不存在。

190839 次浏览

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

no brackets around the function

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

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.

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

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

SELECT myField1
FROM myTable1
WHERE myField1 IS NOT NULL

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: