使用Postgres

时间:2016-07-22 12:42:57

标签: plpgsql postgresql-9.3

我是PostgreSQL的新手,我试图从旧版本转换我们的应用程序中使用的SELECT语句。这样做我在我的第一个SQL SELECT语句中有大约300行SQL代码,其中定义了许多通常从PHP前端填充的局部变量。在尝试转换代码时,我希望在代码的开头定义LOCAL变量,然后只传递那些值。我从PostgreSQL收到了很多错误。任何帮助/方向将不胜感激。感谢。

第一个错误是:

 Error: SQL Error: SQLSTATE[42601]: Syntax error: 7 ERROR: unterminated dollar-quoted string at or near "$$ DECLARE SYEAR numeric" LINE 3: DO $$ ^ Query: DO $$ DECLARE SYEAR numeric Error Info: Array ( [0] => 42601 [1] => 7 [2] => ERROR: unterminated dollar-quoted string at or near "$$ DECLARE SYEAR numeric" LINE 3: DO $$ ^ )  

第二个错误是:

 Error: SQL Error: SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "START_DATE" LINE 2: START_DATE date ^ Query: START_DATE date Error Info: Array ( [0] => 42601 [1] => 7 [2] => ERROR: syntax error at or near "START_DATE" LINE 2: START_DATE date ^ )  

这是我尝试的SQL代码:

DO $$ 
DECLARE 
SYEAR numeric;  
START_DATE date;
END_DATE date; 
SCHOOL_ID numeric; 

BEGIN
    SYEAR := 2015;
    START_DATE := '2015-08-01';
    END_DATE := '2015-12-31';
    SCHOOL_ID := 002;

WITH main AS (
SELECT 
    s.student_id::TEXT, 
    s.last_name || ', ' || s.first_name as student, 
    dailyVisitTotal.count as Number_of_visits,
    dailyVisitTotal.duration_total as Daily_Visit_Total,
    firstAid.count as First_Aid_Visits,
    firstAid.duration_total as First_Aid_Total,
    majorAcc.count as Major_Accident_Visits,
    majorAcc.duration_total as Major_Accident_Total,
    illness.count as Illness_Visits,
    illness.duration_total as Illness_Total,
    medicationAdminTotal.count as Medication_Administration_Visits,
    medicationAdminTotal.duration_total as Medication_Administration_Total,
    specTotal.count as Specialization_Visits,
    specTotal.duration_total as Specialization_Total, 
    diabeticTotal.count as Diabetic_Visits,
    diabeticTotal.duration_total as Diabetic_Total

FROM students s 
LEFT JOIN (
    SELECT 
        sle.student_id, 
        count(sle.*), 
        sum(coalesce(log_field20::numeric, 0)) || ' min' as duration_total 
    FROM student_log_entries_ml sle 
    INNER JOIN student_enrollment se 
        ON (sle.student_id=se.student_id and se.custom_9 is null 
        AND se.syear={SYEAR} 
        AND se.end_date is null)
    INNER JOIN schools sc on (se.school_id=sc.id) 
    WHERE student_field_id = 400000941
        AND log_field2::date between '{START_DATE}' and '{END_DATE}'  
        AND (log_field20 ~ '^[0-9]+$' or log_field20 is null) {SCHOOL_SPECIFIC} 
        AND se.school_id = {SCHOOL_ID}
    GROUP BY sle.student_id
) dailyVisitTotal 
ON (s.student_id = dailyVisitTotal.student_id))
END $$;

0 个答案:

没有答案