Null substitution in SQLite:

久未见 提交于 2019-12-23 12:19:06

问题


In Sybase and MSSqlServer TransactSQL, we have a function IsNull(columnName,valueForNull) to return a typed default value when a column value is null. How can I replicate this functionality in SQLite?

Example in TransactSQL:

select IsNull(MyColumn,-1) as MyColumn from MyTable

If MyColumn is null, this expression will return -1 as the value of MyColumn. Want to do something similar in SQLite.

(Yes, I know I can write my own wrapper function to handle this - that's not the answer I'm looking for)

TIA


回答1:


You can use ifnull:

select ifnull(MyColumn,-1) as MyColumn from MyTable



回答2:


You should use the standard COALESCE function:

select coalesce(MyColumn, -1) as MyColumn from MyTable

Any database that understands standard ANSI SQL will support COALESCE so using it is a good habit to get into.




回答3:


The SQL standard way to do this is with CASE:

 SELECT CASE WHEN MyColumn IS NULL THEN -1 ELSE MyColumn END FROM MyTable

Considerably more verbose than engine-specific IFNULL, ISNULL, NZ functions, but more portable.

(Or, as mu points out, you can use the much better COALESCE for this).




回答4:


SQLite has the IFNULL() built-in function which would do what I think you're trying here.



来源:https://stackoverflow.com/questions/7999608/null-substitution-in-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!