带有变量赋值的Postgresql查询错误

时间:2014-08-07 12:41:58

标签: sql postgresql

希望这个问题很简单。我的postgresql查询需要一些帮助。我想创建一个执行相当复杂事情的函数,所以我不会详细说明。我将发布整个代码以供参考,错误部分(已发布代码的中间位):

编辑:

所有问题都已修复(没有给出任何答案都没有任何帮助)。现在我有一个新问题!

以下是更新后的代码:

CREATE OR REPLACE FUNCTION GetDevicesForPush(alertId INTEGER,appId INTEGER,isTest BOOLEAN,notificationId INTEGER,stateCode VARCHAR) 
    RETURNS "PushDevice" AS
$$
BEGIN
    IF($5 IS NOT NULL) THEN
        BEGIN
            INSERT INTO PushDevice(DeviceId,PushNotificationId, pushId,deviceType,sound)
            SELECT DISTINCT  d.id, $4,d.pushId,d.type,d.sound FROM Device d  inner join DeviceLocation dl ON  d.id = dl.DeviceId 
            WHERE dl.FIPScode in (select FIPScode from CountyFIPS  where stateCode=$5) AND dl.AppId=$2 AND d.pushId is not null and d.pushId <>'' and d.pushId<>'1234-5678-9101-2345-3456' and d.isTest =$3 and d.enableNotification=1 and dl.isDeleted=0
            AND NOT EXISTS (SELECT 1 FROM PushDevice t where t.DeviceId=d.id AND t.PushNotificationId=$4);
        END;
    ELSE 

        DECLARE epiCentre VARCHAR;
                        magnitude FLOAT;

    BEGIN
        SELECT polygon INTO epiCentre from alert  where id=$1 and disablePush=FALSE;
    END;

        IF(epiCentre IS NOT NULL) THEN
        BEGIN
                INSERT INTO PushDevice(DeviceId,PushNotificationId, pushId,deviceType,sound)
                SELECT DISTINCT  d.id, $4,d.pushId,d.type,d.sound FROM Device d  inner join DeviceLocation dl   ON  d.id = dl.DeviceId 
                WHERE  dl.AppId=$2 AND d.pushId is not null and d.pushId <>'' and d.pushId<>'1234-5678-9101-2345-3456' and d.isTest =$3  and ST_Distance_Sphere(ST_GeometryFromText(epiCentre), ST_GeometryFromText(geoPoint))<=d.radius * 1609.344 and magnitude>= d.magnitude and d.enableNotification=1 and dl.isDeleted=0
                AND NOT EXISTS (SELECT 1 FROM PushDevice t where t.DeviceId=d.id AND t.PushNotificationId=$4);
        END;

        SELECT pd.* FROM  PushDevice pd
        WHERE pd.PushNotificationId =$4 and pd.sentAt is null;

END

$$ LANGUAGE plpgsql;

我收到了以下错误:

[Err] ERROR:输入结束时的语法错误 第35行:$$ LANGUAGE plpgsql;

我尝试在END之后加一个分号,完全删除END等等。有人可以告诉我他对此的看法吗?

EDIT2:来吧伙计!我忘记了END IF;声明!!这是错误!

2 个答案:

答案 0 :(得分:0)

我认为问题在于postgresql如何处理decimal和varchar之间的转换。我会使用列中varchar的大小或显式地将小数转换为varchar。

例如:

CAST(severity as decimal(3,1)) INTO magnitude 

尝试使用to_char函数... http://www.postgresql.org/docs/9.0/static/functions-formatting.html

答案 1 :(得分:0)

在最后END

之后必须有一个分号
END;

$$ LANGUAGE plpgsql;