1

I am a beginner in SQL and I don't know how to solve this question. How to combine the following SQL query and the stored procedure into a single SQL query. This is a PostgreSQL query and function. Any help is appreciated.

The following query calls a stored procedure/function for each value of the query:

 SELECT t.trj_id, T2.trj_id, Similar_trj_woffset(t.trj_id, T2.trj_id) 
 FROM   transitions T1, 
        transitions T2 
 WHERE  T1.w_s = T2.w_s 
 AND T1.w_e = T2.w_e 
 AND T1.trans_id <> T2.trans_id 

The stored procedure/function is:

create or replace function similar_trj_woffset(
  IN t1 as integer,
  IN t2 as integer,
  OUT score as integer,
  OUT offset as integer
) AS $$
declare 
off_set integer :=0;
score  integer := 0;
cou    integer;
time1  integer;
time2  integer;
dist   integer;
begin
for off_set in 0..10 LOOP
       time1 := 0;
       time2 := 0 + off_set;
       cou := 0;
       while time2 < 100 Loop 
          select vec_length(P.x-P2.x,P.y-P2.y,P.z-P2.z) into dist
          from AtomPositions P, AtomPositions P2
          where P.trj_id  = t1
            and   P2.trj_id = t2
            and   P.t = time1
            and   P2.t = time2;
        if dist < cuto`enter code here`ff then
            cou : = cou + 1;
        time1 := time1 + 1;
        time2 := time2 + 1;
    end loop
    if cou > score then
       score := cou ;
       offset := off_set;
    end if;
    off_set := off_set + 1;
end loop;

end $$ language plpgsql;

Can some one tell me how to merge the query and the stored procedure into one single SQL query.

4

2 回答 2

1

要调用此函数,将返回的记录拆分为单独的列:

SELECT t.trj_id, t2.trj_id, (similar_trj_woffset(t.trj_id, t2.trj_id)).*
FROM   transitions t1
JOIN   transitions t2 USING (w_s, w_e)
WHERE  t1.trans_id <> t2.trans_id 

请注意函数调用周围的括号。
我还重写了查询以使用正确的 ANSI JOIN 语法和简化的等值连接条件 ( USING),并删除了虚假的大写字母。

于 2013-03-11T07:38:23.047 回答
0

你不应该合并它们是你的基本答案。代码在函数中的一个目的是可以从多个查询中调用它并在一个地方进行维护。当查询已经在每次迭代中调用函数时,合并两者没有意义。

您期望从这样做中获得什么,因为简单地移动代码不会有任何积极意义?

实际上,如果任何其他查询使用它,如果您删除它,它们就会中断。

于 2013-03-10T01:53:08.477 回答