创建存储过程以根据输入参数(id,arrayOfNo [])从员工(第一个表)和订单(第二个表)中删除记录

问题描述 投票:0回答:1

我有两个表,employees(company_id,employee_num)和orders(employee_num,order_description)。

如果用户发送程序参数company_idemploye_num(1,[911,912]),那么如果employees表有更多员工编号为id 1,那么我们应该删除其他员工编号行,如果它有[911,912,913]员工编号为1那么它应该删除从913行作为emp_num并删除命令中的所有记录(表2),其中emp_num是913

离(程序):

    CREATE OR REPLACE FUNCTION deleteEmployeeOrders(P_company_id bigint, orders_array  arrayType[] ) RETURNS INT AS $$
 DECLARE
         orders_array  arrayType;
 DECLARE
         order  arrayType;
 DECLARE
         status_code integer;
 BEGIN
   status_code:= -1;

   FOR line IN (SELECT * FROM employees where company_id = p_company_id)
         LOOP
             if exists(select * from  employees where emp_num = order.emp_num not in orders_array)
THEN
                delete from employees where employee_num = order.employee_num;
                DELETE FROM orders WHERE employee_num = order.employee_num;
         END LOOP;
   status_code = 1;
   return status_code;
 END;
 $$ LANGUAGE plpgsql;

例如

 :select deleteEmployeeOrders(1,[911,912])

它应该在行table1中将913删除为emp no,并删除table2中emp_num 913的所有行

sql postgresql postgresql-9.3 postgresql-9.4
1个回答
0
投票

在您的示例中,听起来您想要删除给定company_id的所有员工(和相关订单)记录。那是对的吗?如果是这样,您可以使用两个简单的DELETE:

-- Delete all orders related to employees for given "company_id"
DELETE FROM orders 
WHERE employee_num IN (
  SELECT employee_num 
  FROM employees 
  WHERE company_id = p_company_id
);

-- Delete employees for given "company_id"
DELETE FROM employees
WHERE company_id = p_company_id;

它们应该在同一个事务中完成,因此它们要么全部工作要么全部失败。您还应首先执行“订单”DELETE,以便您可以引用employees表中的员工。

如果这不是您所需要的,那么请更准确地解释您正在寻找的内容。如果您只指定员工(911,912),我不会完全按照您的示例中的逻辑删除员工913。

更新

修改DELETE语句以针对arrayOfNo数组中不存在的employee_num值运行:

-- Delete all orders related to employees for given "company_id"
DELETE FROM orders 
WHERE employee_num IN (
  SELECT employee_num 
  FROM employees 
  WHERE company_id = p_company_id
  AND employee_num <> ALL(arrayOfNo) -- Get employees NOT IN arrayOfNo list
);

-- Delete employees for given "company_id"
DELETE FROM employees
WHERE company_id = p_company_id
AND employee_num <> ALL(arrayOfNo) -- Get employees NOT IN arrayOfNo list
;

同样,这两个语句应该作为单个事务运行。如果有效,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.