mardi 2 juin 2015

Is there a way to make NULL behave like 0 (zero) or like an empty string in SQL?

Assume a sqlite database with an integer column.

Now, it tends to happen that the integer field contains NULL values (=unset) as well.

I would like to interpret NULL values as zero (0) when doing queries on that field.

Is there a way to tell sqlite that I like NULL handled like 0 in this case, especially when I do comparisons using a SELECT statement?

Since I construct the queries dynamically in C-like code, I like to be able to write something like this:

query = "SELECT * FROM tbl WHERE intField=" + IntToStr(anIntValue)

Currently, I work around this with code as follow, which I like to avoid:

if (anIntValue == 0) {
  query = "SELECT * FROM tbl WHERE intField IS NULL OR intField=0"
} else {
  query = "SELECT * FROM tbl WHERE intField=" + IntToStr(anIntValue)
}

Maybe there's an operator I can use in the query that converts NULLs to other values I specify?

Of course, another way would be to make sure one never ends up with NULL values in that field, but one might want to be able to tell when the value hasn't been set at all yet, so I like to be able to keep the NULL values in the database.

Aucun commentaire:

Enregistrer un commentaire