Firebird和存储过程:如果存在则其他

时间:2013-12-30 17:33:32

标签: stored-procedures if-statement firebird

我正在尝试为firebird 2.1创建一个存储过程(这是要使用的版本) 但是我有点卡住了,所以任何帮助都会受到赞赏。 最终版本应该再次比较表中的4个值,如果值存在则检索primaryid,或者在表中创建新条目,并返回新的primaryid。

但是我只遇到一个值查找,它甚至都没有使用变量。

SET TERM ^ ;

CREATE PROCEDURE TESTSP 
 ( A Varchar(64) ) 
RETURNS 
 ( RESULT Integer )
AS 

BEGIN
IF (EXISTS (SELECT PRIMARYID FROM TABLENAME WHERE FIELD = 'Some string')) then
    SELECT PRIMARYID FROM TABLENAME WHERE FIELD = 'Some string' into :primaryid;
    result = PRIMARYID;
ELSE 
    INSERT INTO TABLENAME (FIELD) VALUES ('Some string');
    result = gen_id(GEN_TABLEID, 0);
END^

SET TERM ; ^

我为Else命令获得了“令牌未知”。

回复后更新: 现在我想使用4个变量并返回4个结果。 我想我需要一个for循环才能这样做,但是对于firebird来说,for函数意味着别的东西。 那么将要走的路是什么?

SET TERM ^ ;

CREATE PROCEDURE TESTSP 
 ( value1 Varchar(64) ) 
RETURNS 
 ( RESULT1 Integer )
AS 

BEGIN
    IF (EXISTS (SELECT PRIMARYID FROM TABLENAME WHERE FIELD = :value1)) then
        SELECT PRIMARYID FROM TABLENAME WHERE FIELD = value1 into :result1;
    ELSE BEGIN
        result1 = gen_id(GEN_TABLEID, 1);
        INSERT INTO TABLENAME (PRIMARYID, FIELD) VALUES (:result1, :value1);
    END
    suspend;
END^

SET TERM ; ^

3 个答案:

答案 0 :(得分:1)

如果你有then和/或else子句的多条指令,你必须使用BEGIN ... END - 阻止!

SET TERM ^ ;

CREATE PROCEDURE TESTSP 
 ( A Varchar(64) ) 
RETURNS 
 ( RESULT Integer )
AS 

BEGIN
IF (EXISTS (SELECT PRIMARYID FROM TABLENAME WHERE FIELD = 'Some string')) then
  BEGIN
    SELECT PRIMARYID FROM TABLENAME WHERE FIELD = 'Some string' into :primaryid;
    result = PRIMARYID;
  END
ELSE 
  BEGIN
    INSERT INTO TABLENAME (FIELD) VALUES ('Some string');
    result = gen_id(GEN_TABLEID, 0);
  END
END^

SET TERM ; ^

答案 1 :(得分:1)

由于Tico已经回答,您必须使用begin / endthen / else部分中的多个语句进行分组。邻居列PRIMARYID未知的错误是因为您在没有为其声明局部变量的情况下引用它。试试这个:

CREATE PROCEDURE TESTSP ( A Varchar(64) ) 
RETURNS ( RESULT Integer )
AS 
BEGIN
  -- initialize the result
  Result = NULL;
  -- check is the string already in table
  SELECT PRIMARYID FROM TABLENAME WHERE FIELD = 'Some string' into :Result;
  IF (Result is NULL) then
    INSERT INTO TABLENAME(PRIMARYID, FIELD) VALUES(gen_id(GEN_TABLEID, 1), 'Some string') RETURNING PRIMARYID INTO :Result;
END^

答案 2 :(得分:1)

我认为您的存储过程应如下所示:

SET TERM ^ ; 
CREATE PROCEDURE TESTSP 
  ( A Varchar(64) ) 
  RETURNS ( result Integer ) 
AS 
BEGIN 
  IF (EXISTS (SELECT PRIMARYID 
              FROM TABLENAME 
              WHERE FIELD = 'Some string')) then 
     SELECT PRIMARYID 
       FROM TABLENAME 
       WHERE FIELD = 'Some string' 
       into :result;
  ELSE BEGIN
     result = gen_id(GEN_TABLEID, 1); 
     INSERT INTO TABLENAME 
       (PRIMARYID, FIELD) 
       VALUES (:result,  'Some string'); 
  END
END^ 
SET TERM ; ^