使用if else和动态sql

时间:2015-09-30 17:06:46

标签: sql tsql

我是动态sql的新手,我试图通过在proc中添加if-else条件来修改现有的存储过程。以下是代码

CREATE PROCEDURE PUBLIC.YEAPOS2Q(IN I_PARAM1 CHARACTER(10), IN I_PARAM2 CHARACTER(8))
MODIFIES SQL DATA DYNAMIC RESULT SETS 1
BEGIN ATOMIC    
    IF (I_PARAM2 IS NULL) THEN
        DECLARE resultSingle CURSOR WITH RETURN FOR SELECT * FROM EMPLOYEE where NAME = I_PARAM1;
    ELSE
        DECLARE resultSingle CURSOR WITH RETURN FOR SELECT * FROM EMPLOYEE where NAME = I_PARAM1 and ID = I_PARAM2;
    END IF;
END;;

运行时出现以下错误:

 HsqlException: unexpected token: DECLARE

有人可以告诉我这里的错误是什么吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

在您的案例中,您不需要IF - 只需检查WHERE子句中的空参数:

DECLARE resultSingle CURSOR 
WITH RETURN FOR 
  SELECT * FROM EMPLOYEE 
  where NAME = I_PARAM1 
    and (I_PARAM2 IS NULL OR ID = I_PARAM2);