SQL 可选 NULL 值
SQL optional NULL value
我不能超过 1 个 sql 字符串。
我有一个可选元素 (#element)。如果未指定,我想从 oper_cd_id_principal
列(包含 NULL 值)中获取任何内容。
如果指定,我可以使用
select * from Table
where oper_cd_id_principal like #element
这会带来我想要的结果。
但是,如果没有指定#element,我可以使用'%'作为#element。它会给我带来除 NULL 值之外的所有值
我看过
select * from Table
where (oper_cd_id_principal like #element OR oper_cd_id_principal IS NULL)
在此示例中,如果未指定#element,它将 return 我需要的结果。
但是如果指定它会给我 oper_cd_id_principal = #element
和 oper_cd_id_principal
.
中的所有其他空值
我该如何解决这个问题?
嗯。 . .我想你想要:
select *
from Table
where oper_cd_id_principal like #element OR
(#element = '%' and oper_cd_id_principal IS NULL)
或者可能:
where coalesce(oper_cd_id_principal, ' ') like #element
您需要小心,因为默认值可能会意外匹配某些字符串。
编辑:
根据您的编辑,您可能需要:
where oper_cd_id_principal = #element or
(oper_cd_id_principal is null and #element is null)
我使用了您代码的变体
其中 oper_cd_id_principal = #element 或
(oper_cd_id_principal 为空且#element 为空)
至
其中 oper_cd_id_principal 喜欢 #element 或
(oper_cd_id_principal 为空且#element = '%')
如果指定了元素,它只会给我带来 column = element 的结果。 OR 被忽略
如果未指定元素,我可以将空值从#element 转换为“%”。
所以这部分(oper_cd_id_principal 像#element)给我带来了 oper_cd_id_principal 不为 NULL 的每一行,而 OR 部分给我带来了每一行 NULL
我不能超过 1 个 sql 字符串。
我有一个可选元素 (#element)。如果未指定,我想从 oper_cd_id_principal
列(包含 NULL 值)中获取任何内容。
如果指定,我可以使用
select * from Table
where oper_cd_id_principal like #element
这会带来我想要的结果。 但是,如果没有指定#element,我可以使用'%'作为#element。它会给我带来除 NULL 值之外的所有值
我看过
select * from Table
where (oper_cd_id_principal like #element OR oper_cd_id_principal IS NULL)
在此示例中,如果未指定#element,它将 return 我需要的结果。
但是如果指定它会给我 oper_cd_id_principal = #element
和 oper_cd_id_principal
.
我该如何解决这个问题?
嗯。 . .我想你想要:
select *
from Table
where oper_cd_id_principal like #element OR
(#element = '%' and oper_cd_id_principal IS NULL)
或者可能:
where coalesce(oper_cd_id_principal, ' ') like #element
您需要小心,因为默认值可能会意外匹配某些字符串。
编辑:
根据您的编辑,您可能需要:
where oper_cd_id_principal = #element or
(oper_cd_id_principal is null and #element is null)
我使用了您代码的变体
其中 oper_cd_id_principal = #element 或 (oper_cd_id_principal 为空且#element 为空)
至
其中 oper_cd_id_principal 喜欢 #element 或 (oper_cd_id_principal 为空且#element = '%')
如果指定了元素,它只会给我带来 column = element 的结果。 OR 被忽略
如果未指定元素,我可以将空值从#element 转换为“%”。 所以这部分(oper_cd_id_principal 像#element)给我带来了 oper_cd_id_principal 不为 NULL 的每一行,而 OR 部分给我带来了每一行 NULL