检查所有行是否与给定条件匹配

时间:2009-07-09 11:51:19

标签: sql oracle plsql

requestId   Consultantid  statusid
1           2             10
2           2             10
3           2             10

我想检查每一行的statusid是否为10。

if (every row has a statusid of 10) then
  -----do this
endif;

3 个答案:

答案 0 :(得分:1)

我对PL-SQL有点生疏,但是这样的东西可以在T-SQL中使用:

 if not exists (select * from your_table where statusid <> 10) then
    -- whatever
 end

修改 好吧,显然在PL-SQL中,你需要做这样的事情:

DECLARE
  notallten INTEGER;
BEGIN
  SELECT COUNT(*) INTO notallten 
  FROM your_table
  WHERE statusid <> 10
  AND ROWNUM = 1;
  IF notallten = 0 THEN
    -- Do something
  END IF;
END;

我没有要测试的Oracle服务器。

答案 1 :(得分:0)

declare
v_exists_status_10 number(1);
...

begin
...
-- v_exists_status_10 = 0 if no such row exist, 1 if at least one does
select count(*)
into   v_exists_status_10
from   dual
where  exists
  (select * from your_table where statusid <> 10);

if v_exists_status_10 > 0 then
...

请注意,您也可以对变量执行一个愚蠢的COUNT(),但与EXISTS相比,它可能会非常低效。使用COUNT(),你必须扫描所有记录,而只要它达到statusid = 10就有EXISTS,它就可以停止扫描。

答案 2 :(得分:0)

更简单的解决方案,在statusid中考虑NULL:

for r in (
  select 1 dummy
  from   your_table
  where  (statusid != 10 or statusid is null)
  and    rownum = 1) loop
    -----do this
end loop;