PL / SQL Update命令不更新数据库中的记录

时间:2017-05-30 20:14:44

标签: sql plsql

我在下面写了存储过程

CREATE OR REPLACE PROCEDURE EmployeeProcedure
(id IN NUMBER, name IN VARCHAR, salary IN NUMBER,
stmt IN VARCHAR
) AS

BEGIN
IF stmt='INSERT' then
     INSERT INTO Employee(employee_id,name,salary) VALUES(id, name, salary);
END IF;

IF stmt='UPDATE' then
     update employee set name=name, salary=salary
         where employee_id=id;
END IF;

IF stmt='DELETE' then
   Delete from employee where employee_id=id;
END IF;

END EmployeeProcedure;

这是Employee表中可用的数据

EMPLOYEE_ID NAME    SALARY  TITLE
2   Ranjan  40000   Manager
3   Stella  5000    President
4   Fred    500 Janitor
10  Ranjan  3000    -
1   John    64876   -

当我使用以下语句

执行此存储过程时
begin
EmployeeProcedure(10,'John',78987,'UPDATE');
end;

我正在处理声明。但是员工id = 10的记录没有得到更新。任何帮助将非常感谢!!

3 个答案:

答案 0 :(得分:0)

不要使用与您要更新的字段同名的变量

这不会做任何事情:

 SET name = name, salary = salary

将变量设置为:

 str_name,  int_salary

然后你会有

 SET name = str_name, salary = int_salary

答案 1 :(得分:0)

我不会在调用您的程序或程序本身时看到提交。

如果您的执行是从您声明的匿名块运行的,请务必事后发出提交。

同样正如Juan Carlos Oropeza所说,让你的参数与列名相同,已被证明是一种不好的做法,附加信件" p"区分参数和列名称,如:

CREATE OR REPLACE PROCEDURE EmployeeProcedure
(p_id IN NUMBER, p_name IN VARCHAR, p_salary IN NUMBER,
p_stmt IN VARCHAR
) AS

BEGIN
IF p_stmt='INSERT' then
     INSERT INTO Employee(employee_id,name,salary) VALUES(p_id, p_name, p_salary);
END IF;

IF p_stmt='UPDATE' then
     update employee set name=p_name, salary=p_salary
         where employee_id=p_id;
END IF;

IF p_stmt='DELETE' then
   Delete from employee where employee_id=p_id;
END IF;

END EmployeeProcedure;

答案 2 :(得分:0)

很高兴我帮了忙。

关于在你的过程中使用'select'语句,我认为你必须做一点改变来实现一个返回值,因为在PL / SQL块中使用select语句是不可能的,除非你在显式/隐式游标中使用它。

我想这样的事情可以做到:

create or replace PROCEDURE EmployeeProcedure(
    p_id IN NUMBER, 
    p_name IN VARCHAR, 
    p_salary IN NUMBER,
    p_stmt IN VARCHAR, 
    p_CURSOR in out SYS_REFCURSOR
) AS 
BEGIN
    IF p_stmt='INSERT' then
         INSERT INTO Employee(employee_id,name,salary) VALUES(p_id, p_name, p_salary);
    END IF;

    IF p_stmt='UPDATE' then
         update employee set name=p_name, salary=p_salary
             where employee_id=p_id;
    END IF;

    IF p_stmt='DELETE' then
       Delete from employee where employee_id=p_id;
    END IF;

    IF p_stmt='SELECT' then
        /*open the explicit cursor*/
        open p_cursor for
            select * 
            from employee 
            where employee_id = p_id;
    END IF;

END EmployeeProcedure;

然后你必须以这种方式阅读光标:

declare
    cur       SYS_REFCURSOR;
    data_row  employee%rowtype;
begin
    EmployeeProcedure(1,null,null,'SELECT', cur);--opens cursor
    loop 
        fetch cur into data_row; --reads one row
        exit when cur%notfound; --exits when you reach the end of rows

        --at this point you can access every row in your table.
        dbms_output.put_line(data_row.employee_id);
    end loop;
    close cur; --always remember close every cursor you open to keep your DBA happy.
 end;