Oracle SQL中的Null情况

huangapple go评论56阅读模式
英文:

Oracle SQL Case with Null

问题

我有一个简单的查询,它从一个绑定变量中获取输入。

CREATE TABLE "FRUITS" 
(	"FRUIT_NAME" VARCHAR2(100), 
	"COLOR" VARCHAR2(100)
) ;

insert into fruits (fruit_name, color)
values ('Banana', 'Yellow')
insert into fruits (fruit_name, color)
values ('Lemon', '')
insert into fruits (fruit_name, color)
values ('Apple', 'Red')

SELECT * FROM FRUITS
WHERE
COLOR =     case
            when :P1_ITEM is null then null
            else :P1_ITEM
            end

如果输入为'Yellow',结果将是'Banana'(如果为'Red',则为'Apple')。然而,如果输入恰好为null,结果将是'未找到数据'。

如何避免这种情况,因为null不是null值呢?
如果颜色为空,那么如何返回颜色为空的行?也就是'Lemon' + null

谢谢

英文:

I have a simple query that is taking an input from a bind variable.

CREATE TABLE "FRUITS" 
(	"FRUIT_NAME" VARCHAR2(100), 
"COLOR" VARCHAR2(100)
) ;

insert into fruits (fruit_name, color)
values ('Banana', 'Yellow')
insert into fruits (fruit_name, color)
values ('Lemon', '')
insert into fruits (fruit_name, color)
values ('Apple', 'Red')

SELECT * FROM FRUITS
WHERE
COLOR =     case
            when :P1_ITEM is null then null
            else :P1_ITEM
            end

If the input is 'Yellow' the result would be 'Banana' (when 'Red' then 'Apple'). However, if the input happens to be null the result is 'no data found'.
How can this be avoided knowing that null is not a null value?
If the input is null on color then how can I return the null color row? meaning 'Lemon' + null

Thanks

答案1

得分: 1

以下是翻译好的部分:

"Something like this might be one option:

SELECT * FROM FRUITS
WHERE
nvl(COLOR, 'x') = case
when :P1_ITEM is null then 'x'
else :P1_ITEM
end;"

英文:

Something like this might be one option:

SELECT * FROM FRUITS
WHERE
nvl(COLOR, 'x') = case
                    when :P1_ITEM is null then 'x'
                    else :P1_ITEM
                  end;

huangapple
  • 本文由 发表于 2023年6月2日 02:33:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76384755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定