使用随机等级更新表

时间:2015-11-17 03:14:17

标签: postgresql for-loop insert-update

我有一个功能,旨在根据学生人数和每个学生获得该学校特定年级的概率,为特定学校分配成绩。 我已经把所有这些概率降低了但是在尝试用正确的等级更新表时会出现错误。 我不知道我是否正在更新错误或将更新放在正确的区域。

 CREATE FUNCTION assigngrades(probs numeric[], school text, record_id bigint) RETURNS void AS $$
 DECLARE
num_grades integer ARRAY[6];
found_school school_probs%ROWTYPE;
num_students simulated_records%ROWTYPE;
random_record simulated_records%ROWTYPE;
num_students_int bigint;



BEGIN
SELECT INTO found_school * FROM school_probs WHERE school_code = record_id;
SELECT INTO num_students * FROM simulated_records WHERE school = school_name;
SELECT COUNT(*) INTO num_students_int FROM simulated_records WHERE school = school;

num_grades[1] = num_students_int*found_school.probs[1];
num_grades[2] = num_students_int*found_school.probs[1];
num_grades[3] = num_students_int*found_school.probs[1];
num_grades[4] = num_students_int*found_school.probs[1];
num_grades[5] = num_students_int*found_school.probs[1];
num_grades[6] = num_students_int*found_school.probs[1];

FOR i IN 1..num_grades[1] LOOP

    SELECT INTO random_record * FROM simulated_records WHERE school = school_name ORDER BY RANDOM() LIMIT 1;
    IF random_record.grade = '-' THEN
       random_record.grade = 'A';

END IF;
UPDATE simulated_records.grade = random_record.grade;
END Loop; 

FOR i IN 1..num_grades[2] LOOP

    SELECT INTO random_record * FROM simulated_records WHERE school = school_name ORDER BY RANDOM() LIMIT 1;
    IF random_record.grade = '-' THEN
        random_record.grade := 'A-';
END IF;
UPDATE simulated_records.grade = random_record.grade;
END Loop; 
FOR i IN 1..num_grades[3] LOOP

    SELECT INTO random_record * FROM simulated_records WHERE school = school_name ORDER BY RANDOM() LIMIT 1;
    IF random_record.grade = '-' THEN
        random_record.grade := 'B+';
END IF;
UPDATE simulated_records.grade = random_record.grade;
END Loop; 
FOR i IN 1..num_grades[4] LOOP

    SELECT INTO random_record * FROM simulated_records WHERE school = school_name ORDER BY RANDOM() LIMIT 1;
    IF random_record.grade = '-' THEN
        random_record.grade := 'B';
END IF;
UPDATE simulated_records.grade = random_record.grade;
END Loop; 
FOR i IN 1..num_grades[5] LOOP

    SELECT INTO random_record * FROM simulated_records WHERE school = school_name ORDER BY RANDOM() LIMIT 1;
    IF random_record.grade = '-' THEN
        random_record.grade := 'C';
END IF;
UPDATE simulated_records.grade = random_record.grade;
END Loop; 
FOR i IN 1..num_grades[6] LOOP

    SELECT INTO random_record * FROM simulated_records WHERE school = school_name ORDER BY RANDOM() LIMIT 1;
    IF random_record.grade = '-' THEN
         random_record.grade = 'D';

END IF;
UPDATE simulated_records.grade = random_record.grade;

END Loop; 

END;
$$
LANGUAGE plpgsql

老实说,我只是不确定如何正确更新它。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您的WHERE命令中需要UPDATE子句,因为

UPDATE simulated_records.grade = random_record.grade;

更新表格的所有行。