更新函数PostgreSQL的句子

时间:2015-01-04 07:00:49

标签: postgresql stored-procedures plpgsql

我有以下代码可以使用:

UPDATE backup_factura 
    SET tipo = CASE 
                 WHEN total_fact <=100 THEN 'X'
                 WHEN total_fact <=200 THEN 'Y'
                 ELSE 'Z'
               END
RETURNING *; 

我的老师让我把它转换成一个功能。 我尝试过以下方法:

CREATE Function sp_test_case () returns void as $$ 
BEGIN

  UPDATE backup_factura 
    SET tipo = CASE 
                 WHEN total_fact <=100 THEN 'X'
                 WHEN total_fact <=200 THEN 'Y'
                 ELSE 'Z'
               END
  RETURNING *;

RETURN;   
END;   
$$ LANGUAGE plpgsql; 

但是当我执行该功能时,我得到:

********** Error **********
ERROR: query has no destination for result data
SQL state: 42601
Context: PL / pgSQL sp_test_case () function in line 4 SQL statement

我也试过更复杂的方法:

CREATE Function sp_test_case () returns void as $$ 
DECLARE
    cont int=(Select MAX(id_fact)from backup_factura);
BEGIN

  while cont>0
  LOOP

    UPDATE backup_factura
    SET tipo= CASE 
            WHEN ((total_fact) <=100) THEN 'X'
            WHEN ((total_fact) <=200) THEN 'Y'
            ELSE 'Z'
           END;

    WHERE id_fact=cont;

    cont:=cont-1;

   END LOOP;

RETURN;   
END;   
$$ LANGUAGE plpgsql; 

但我明白了:

********** Error **********
ERROR: syntax error at or near "WHERE"
SQL state: 42601
Character: 283

重点是显示如下:

Table

2 个答案:

答案 0 :(得分:1)

您可以使用return query语法并返回setof您的表格:

CREATE Function sp_test_case () RETURNS SETOF backup_factura AS $$ 
BEGIN

  RETURN QUERY
  UPDATE backup_factura 
    SET tipo = CASE 
                 WHEN total_fact <=100 THEN 'X'
                 WHEN total_fact <=200 THEN 'Y'
                 ELSE 'Z'
               END
  RETURNING *;
END;   
$$ LANGUAGE plpgsql; 

答案 1 :(得分:1)

你可以像@Mureinik发布的那样修复你的plpgsql函数。或者,更好的是,使用更简单的SQL function

CREATE FUNCTION sp_test_case ()
   RETURNS SETOF backup_factura AS
$func$
UPDATE backup_factura 
SET    tipo = CASE WHEN total_fact <= 100 THEN 'X'
                   WHEN total_fact <= 200 THEN 'Y'
                   ELSE 'Z' END
RETURNING *;
$func$ LANGUAGE sql; 

呼叫:

SELECT * FROM sp_test_case();