Как будто вы пытаетесь получить доступ к объекту, который является null
. Рассмотрим ниже пример:
TypeA objA;
. В это время вы только что объявили этот объект, но не инициализировали или не инициализировали. И всякий раз, когда вы пытаетесь получить доступ к каким-либо свойствам или методам в нем, он будет генерировать NullPointerException
, что имеет смысл.
См. Также этот пример:
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
завершенный синтаксис зависит от механизма базы данных, с которым Вы работаете:
Для SQL Server:
CASE case-expression
WHEN when-expression-1 THEN value-1
[ WHEN when-expression-n THEN value-n ... ]
[ ELSE else-value ]
END
или:
CASE
WHEN boolean-when-expression-1 THEN value-1
[ WHEN boolean-when-expression-n THEN value-n ... ]
[ ELSE else-value ]
END
выражения, и т.д.:
case-expression - something that produces a value
when-expression-x - something that is compared against the case-expression
value-1 - the result of the CASE statement if:
the when-expression == case-expression
OR the boolean-when-expression == TRUE
boolean-when-exp.. - something that produces a TRUE/FALSE answer
Ссылка: СЛУЧАЙ (Transact-SQL)
Также примечание, что упорядочивание, КОГДА операторы важно. Можно легко записать нескольким, КОГДА пункты, которые накладываются, и первый, который соответствия используются .
Примечание : Если никакое Выражение else не будет определено, и никакое КОГДА-УСЛОВИЕ соответствия не найдено, значение выражения CASE будет ПУСТОЙ УКАЗАТЕЛЬ .
Один момент, который необходимо отметить, в случае Oracle, если не, когда соответствия и существуют не еще, разделяют исключение, повышен.
Рассмотрение Вас отметило несколько продуктов, я скажу полный , правильный синтаксис был бы тем, найденным в стандарте ISO/ANSI SQL-92:
<case expression> ::=
<case abbreviation>
| <case specification>
<case abbreviation> ::=
NULLIF <left paren> <value expression> <comma>
<value expression> <right paren>
| COALESCE <left paren> <value expression>
{ <comma> <value expression> }... <right paren>
<case specification> ::=
<simple case>
| <searched case>
<simple case> ::=
CASE <case operand>
<simple when clause>...
[ <else clause> ]
END
<searched case> ::=
CASE
<searched when clause>...
[ <else clause> ]
END
<simple when clause> ::= WHEN <when operand> THEN <result>
<searched when clause> ::= WHEN <search condition> THEN <result>
<else clause> ::= ELSE <result>
<case operand> ::= <value expression>
<when operand> ::= <value expression>
<result> ::= <result expression> | NULL
<result expression> ::= <value expression>
Синтаксические правила
1) NULLIF (V1, V2) is equivalent to the following <case specification>:
CASE WHEN V1=V2 THEN NULL ELSE V1 END
2) COALESCE (V1, V2) is equivalent to the following <case specification>:
CASE WHEN V1 IS NOT NULL THEN V1 ELSE V2 END
3) COALESCE (V1, V2, . . . ,n ), for n >= 3, is equivalent to the
following <case specification>:
CASE WHEN V1 IS NOT NULL THEN V1 ELSE COALESCE (V2, . . . ,n )
END
4) If a <case specification> specifies a <simple case>, then let CO
be the <case operand>:
a) The data type of each <when operand> WO shall be comparable
with the data type of the <case operand>.
b) The <case specification> is equivalent to a <searched case>
in which each <searched when clause> specifies a <search
condition> of the form "CO=WO".
5) At least one <result> in a <case specification> shall specify a
<result expression>.
6) If an <else clause> is not specified, then ELSE NULL is im-
plicit.
7) The data type of a <case specification> is determined by ap-
plying Subclause 9.3, "Set operation result data types", to the
data types of all <result expression>s in the <case specifica-
tion>.
Access Rules
None.
General Rules
1) Case:
a) If a <result> specifies NULL, then its value is the null
value.
b) If a <result> specifies a <value expression>, then its value
is the value of that <value expression>.
2) Case:
a) If the <search condition> of some <searched when clause> in
a <case specification> is true, then the value of the <case
specification> is the value of the <result> of the first
(leftmost) <searched when clause> whose <search condition> is
true, cast as the data type of the <case specification>.
b) If no <search condition> in a <case specification> is true,
then the value of the <case expression> is the value of the
<result> of the explicit or implicit <else clause>, cast as
the data type of the <case specification>.
Вот CASE
примеры оператора из документов PostgreSQL (Пост-ГРЭС следует стандарту SQL здесь):
SELECT a,
CASE WHEN a=1 THEN 'one'
WHEN a=2 THEN 'two'
ELSE 'other'
END
FROM test;
или
SELECT a,
CASE a WHEN 1 THEN 'one'
WHEN 2 THEN 'two'
ELSE 'other'
END
FROM test;
, Очевидно, вторая форма является более чистой, когда Вы просто проверяете одно поле по списку возможных значений. Первая форма позволяет более сложные выражения.
Я вскопал страницу Oracle для того же, и похоже, что это - тот же синтаксис, просто описал немного отличающийся.
Ссылка: Oracle/PLSQL: Оператор выбора
Синтаксис Oracle из 11-граммовой Документации:
CASE { simple_case_expression | searched_case_expression }
[ else_clause ]
END
simple_case_expression
expr { WHEN comparison_expr THEN return_expr }...
searched_case_expression
{ WHEN condition THEN return_expr }...
else_clause
ELSE else_expr
Sybase имеет тот же синтаксис случая как SQL Server:
Условные SQL-выражения поддержек; может использоваться где угодно, выражение может использоваться.
case
when search_condition then expression
[when search_condition then expression]...
[else expression]
end
case expression
when expression then expression
[when expression then expression]...
[else expression]
end
начинает case-выражение.
предшествует условию поиска или выражению, которое будет сравнено.
используется для устанавливания условий для результатов, которые выбраны. Условия поиска для case-выражений подобны условиям поиска в где пункт. Условия поиска детализированы в Руководстве пользователя Transact-SQL.
предшествует выражению, которое указывает значение результата случая.
имя столбца, константа, функция, подзапрос или любая комбинация имен столбцов, констант и функций, соединенных арифметическими или побитовыми операторами. Для получения дополнительной информации о выражениях, см. “Выражения” в.
select disaster,
case
when disaster = "earthquake"
then "stand in doorway"
when disaster = "nuclear apocalypse"
then "hide in basement"
when monster = "zombie apocalypse"
then "hide with Chuck Norris"
else
then "ask mom"
end
from endoftheworld