Oracle PL/SQL 似乎忽略了我函数的 WHERE 子句
Oracle PL/SQL seems to ignore WHERE clause of my Function
我有一个 table 的俱乐部成员,他们有一列状态,我想在下面的函数中用作过滤器。但是无论我将什么数字作为函数参数传递,结果总是相同的。计数始终与整个 table.
的总寄存器一起出现
CREATE OR REPLACE FUNCTION fn_count_members
(id_status in club.members.id_status%TYPE)
RETURN NUMBER IS
total club.members.id%TYPE:=0;
BEGIN
SELECT COUNT(id) INTO total
FROM club.members m
WHERE m.id_status = id_status;
RETURN total;
END;
以及查询:
select id_status, fn_count_members(1) as total from club.members;
我在这里错过了什么?
谢谢。
这是错误的:
(id_status in club.members.id_status%TYPE)
---------
this
因为,在 where
子句中使用时
WHERE m.id_status = id_status
原来是where 1 = 1
和returns一切,根本没有过滤。
将参数重命名为例如
(par_id_status in club.members.id_status%TYPE)
并将其用作
WHERE m.id_status = par_id_status
您有两个问题:
CREATE OR REPLACE FUNCTION fn_count_members(
p_id_status in club.members.id_status%TYPE -- change the parameter name to
-- something different from the
-- column name.
)
RETURN NUMBER IS
total club.members.id%TYPE:=0;
BEGIN
SELECT COUNT(id) INTO total
FROM club.members m
WHERE m.id_status = p_id_status; -- and here
RETURN total;
END;
/
那你需要传入参数而不是使用1
:
select id_status,
fn_count_members(id_status) as total
from club.members;
db<>fiddle here
我有一个 table 的俱乐部成员,他们有一列状态,我想在下面的函数中用作过滤器。但是无论我将什么数字作为函数参数传递,结果总是相同的。计数始终与整个 table.
的总寄存器一起出现CREATE OR REPLACE FUNCTION fn_count_members
(id_status in club.members.id_status%TYPE)
RETURN NUMBER IS
total club.members.id%TYPE:=0;
BEGIN
SELECT COUNT(id) INTO total
FROM club.members m
WHERE m.id_status = id_status;
RETURN total;
END;
以及查询:
select id_status, fn_count_members(1) as total from club.members;
我在这里错过了什么? 谢谢。
这是错误的:
(id_status in club.members.id_status%TYPE)
---------
this
因为,在 where
子句中使用时
WHERE m.id_status = id_status
原来是where 1 = 1
和returns一切,根本没有过滤。
将参数重命名为例如
(par_id_status in club.members.id_status%TYPE)
并将其用作
WHERE m.id_status = par_id_status
您有两个问题:
CREATE OR REPLACE FUNCTION fn_count_members(
p_id_status in club.members.id_status%TYPE -- change the parameter name to
-- something different from the
-- column name.
)
RETURN NUMBER IS
total club.members.id%TYPE:=0;
BEGIN
SELECT COUNT(id) INTO total
FROM club.members m
WHERE m.id_status = p_id_status; -- and here
RETURN total;
END;
/
那你需要传入参数而不是使用1
:
select id_status,
fn_count_members(id_status) as total
from club.members;
db<>fiddle here