oracle sql求1-100之间的素数

要找出1-100之间的素数,你可以使用以下Oracle SQL查询:

sql
SELECT number  
FROM (SELECT 1 AS number FROM dual  
      UNION ALL  
      SELECT 2 AS number FROM dual  
      UNION ALL  
      SELECT 3 AS number FROM dual  
      UNION ALL  
      SELECT 4 AS number FROM dual  
      UNION ALL  
      SELECT 5 AS number FROM dual  
      UNION ALL  
      SELECT 6 AS number FROM dual  
      UNION ALL  
      SELECT 7 AS number FROM dual  
      UNION ALL  
      SELECT 8 AS number FROM dual  
      UNION ALL  
      SELECT 9 AS number FROM dual  
      UNION ALL  
      SELECT 10 AS number FROM dual)  
WHERE number <= 100 AND NOT EXISTS (  
    SELECT 1 FROM (SELECT 2 AS n, n + 1 AS next_n FROM dual CONNECT BY n <= 100 ORDER BY n)  
    WHERE number * next_n = n * (n + 1)  
);
这个查询首先创建了一个临时的数字表,其中包含从1到10的数字。然后,它使用NOT EXISTS子查询来排除那些可以被整除的数字。如果一个数字number乘以它的下一个数字next_n等于n * (n + 1),那么这个数字就不是素数。最后,查询返回所有小于或等于100的素数。

您也可以以下的SQL会简单些

declare
fagboolean:=true;
begin
for i in1..100 loop
for j in 2..i-1 loop
if mod(i,j)=0 then
fag:=false;
end if;
end loop;
if fag then
dbms_output.put_line(i);
end if;
fag:=true;
end loop;

end;
 

你可能感兴趣的:(oracle,sql,数据库)