当我执行修改表的功能时,更改表失败

时间:2019-01-09 08:21:29

标签: postgresql function plpgsql ddl

我写了一个通用函数来更改ID错误的学生的ID。由于students表被其他表引用,因此我必须删除外键并暂时禁用触发器。这是我的职责。

CREATE OR REPLACE FUNCTION update_student_id(varchar, varchar) RETURNS varchar AS $$
DECLARE 
old_id ALIAS FOR  $1;
new_id ALIAS FOR  $2;
msg varchar(120);

BEGIN

    --disable triggers
   ALTER TABLE students
   DISABLE TRIGGER ALL;

    ALTER TABLE studentdegrees
    DISABLE TRIGGER ALL;


    ALTER TABLE studentdegrees DROP CONSTRAINT studentdegrees_studentid_fkey;
    UPDATE students 
    SET studentid=new_id
    WHERE studentid=old_id;

    ALTER TABLE studentdegrees
    ADD CONSTRAINT studentdegrees_studentid_fkey
    FOREIGN KEY (studentid)
    REFERENCES students(studentid);

    UPDATE studentdegrees 
    SET studentid=new_id
    WHERE studentid=old_id;

    UPDATE entitys 
    SET user_name=new_id
    WHERE user_name=old_id;

    --enable triggers
    ALTER TABLE students
    ENABLE TRIGGER ALL;

    ALTER TABLE studentdegrees
    ENABLE TRIGGER ALL;

    msg:=old_id|| ' Changed to '||new_id;

RETURN msg;
END;
$$ LANGUAGE plpgsql; 

当我这样调用函数

SELECT  update_student_id(
studentid, a.stdid)
FROM
(SELECT studentid,  REPLACE(studentid, ' ', '') AS stdid
FROM students
WHERE studentid NOT IN (SELECT REPLACE(studentid, ' ', ''))) AS a

我收到此错误

  

错误:此会话中的活动查询正在使用它来更改ALTER TABLE“学生”
  上下文:SQL语句“ ALTER TABLE studentdegrees DROP CONSTRAINT studentdegrees_studentid_fkey”
  SQL语句中的PL / pgSQL函数update_student_id(字符变化,字符变化)第17行

0 个答案:

没有答案