创建函数时创建或附近的postgresql语法错误

时间:2013-12-02 11:36:35

标签: postgresql

我正在尝试在postgresql中创建一个函数, 有些功能起作用,其他功能出错, 代码是:

 Create or replace function CalcScore(Drive_name varchar,FromPlanet varchar, ToPlanet varchar)  returns integer as $$
    declare
        driverLoc Locations%ROWTYPE;
        fromLoc Locations%ROWTYPE;
        toLoc Locations%ROWTYPE;
        plantDist integer;
        driverDist integer;
    begin
    SELECT * FROM Location INTO driverLoc
    WHERE Name=Drive_name;
    SELECT * FROM Location INTO fromLoc
    WHERE Name=FromPlanet;
    SELECT * FROM Location INTO toLoc
    WHERE Name=ToPlanet;
    plantDist :=floor(sqrt(
            (fromLoc.X - toLoc.X)*(fromLoc.X - toLoc.X) + 
            (fromLoc.Y - toLoc.Y)*(fromLoc.Y - toLoc.Y)+
            (fromLoc.Z - toLoc.Z)*(fromLoc.Z - toLoc.Z)
            ));
    driverDist :=floor(sqrt(
            (fromLoc.X - driverLoc.X)*(fromLoc.X - driverLoc.X) + 
            (fromLoc.Y - driverLoc.Y)*(fromLoc.Y - driverLoc.Y)+
            (fromLoc.Z - driverLoc.Z)*(fromLoc.Z - driverLoc.Z)
            ));
    return planetDist-DriverDist;
    end;
    $$language plpgsql;

我得到的错误是:

57: ERROR:  syntax error at or near "Create"
LINE 25: Create or replace function CalcScore(Drive_name varchar,From...

我也得到其他功能的错误。 表'位置'存在,有什么想法吗?

1 个答案:

答案 0 :(得分:1)

此代码中有两个错误:

变量声明使用Locations%ROWTYPE(location * s * - with“s”    最后),同时SELECT * FROM Location INTO语句引用    Location表(不含“s”)。

return planetDist-DriverDist;    引用Plan**e**tDist
虽然声明plantDist integer;    (没有“e”)



修复这两个错误后,函数编译并正常工作,见这个演示:http://www.sqlfiddle.com/#!1/38d68/1

Create or replace function CalcScore(Drive_name varchar,FromPlanet varchar, ToPlanet varchar)  returns integer as $$
    declare
        driverLoc Locations%ROWTYPE;
        fromLoc Locations%ROWTYPE;
        toLoc Locations%ROWTYPE;
        plantDist integer;
        driverDist integer;
    begin
    SELECT * FROM Locations INTO driverLoc
    WHERE Name=Drive_name;
    SELECT * FROM Locations INTO fromLoc
    WHERE Name=FromPlanet;
    SELECT * FROM Locations INTO toLoc
    WHERE Name=ToPlanet;
    plantDist :=floor(sqrt(
            (fromLoc.X - toLoc.X)*(fromLoc.X - toLoc.X) + 
            (fromLoc.Y - toLoc.Y)*(fromLoc.Y - toLoc.Y)+
            (fromLoc.Z - toLoc.Z)*(fromLoc.Z - toLoc.Z)
            ));
    driverDist :=floor(sqrt(
            (fromLoc.X - driverLoc.X)*(fromLoc.X - driverLoc.X) + 
            (fromLoc.Y - driverLoc.Y)*(fromLoc.Y - driverLoc.Y)+
            (fromLoc.Z - driverLoc.Z)*(fromLoc.Z - driverLoc.Z)
            ));
    return plantDist-DriverDist;
    end;
    $$language plpgsql/