oracle 存储过程优秀例子
Oracle存储过程是一种在数据库中存储和执行SQL语句的过程。它可以接受参数并返回结果,用于实现复杂的业务逻辑和数据操作。下面是10个优秀的Oracle存储过程示例,展示了不同方面的功能和用法。
1. 创建表并插入数据
```sql
CREATE PROCEDURE create_employee_table AS
BEGIN
  EXECUTE IMMEDIATE 'CREATE TABLE employee (id NUMBER, name VARCHAR2(100))';
  EXECUTE IMMEDIATE 'INSERT INTO employee VALUES (1, ''John Doe'')';
  EXECUTE IMMEDIATE 'INSERT INTO employee VALUES (2, ''Jane Smith'')';
END;
```
这个存储过程创建了一个名为employee的表,并插入了两条数据。
2. 更新员工姓名
```sql
CREATE PROCEDURE update_employee_name(p_id NUMBER, p_name VARCHAR2) AS
BEGIN
  UPDATE employee SET name = p_name WHERE id = p_id;
  COMMIT;
END;
```
这个存储过程接受员工的ID和新的姓名作为参数,然后更新对应员工的姓名。
3. 删除员工记录
```sql
CREATE PROCEDURE delete_employee(p_id NUMBER) AS
BEGIN
  DELETE FROM employee WHERE id = p_id;
  COMMIT;
END;
```
这个存储过程接受员工的ID作为参数,然后删除对应的员工记录。
4. 查询员工信息
```sql
CREATE PROCEDURE get_employee(p_id NUMBER) AS
  CURSOR c_employee IS
    SELECT * FROM employee WHERE id = p_id;
  v_employee employee%ROWTYPE;
BEGIN
  OPEN c_employee;
  FETCH c_employee INTO v_employee;
  CLOSE c_employee;
 
  DBMS_OUTPUT.PUT_LINE('ID: ' || v_employee.id || ', Name: ' || v_employee.name);
END;
```
这个存储过程接受员工的ID作为参数,然后查询对应员工的信息并输出。
5. 计算员工数量
```sql
CREATE PROCEDURE count_employees AS
  v_count NUMBER;
BEGIN
  SELECT COUNT(*) INTO v_count FROM employee;
 
  DBMS_OUTPUT.PUT_LINE('Total Employees: ' || v_count);
END;
sql存储过程实例
```
这个存储过程计算员工表中的记录数量,并输出结果。
6. 根据条件查询员工
```sql
CREATE PROCEDURE search_employees(p_name VARCHAR2) AS
  CURSOR c_employees IS
    SELECT * FROM employee WHERE name LIKE '%' || p_name || '%';
  v_employee employee%ROWTYPE;
BEGIN
  OPEN c_employees;
  LOOP
    FETCH c_employees INTO v_employee;
    EXIT WHEN c_employees%NOTFOUND;
   
    DBMS_OUTPUT.PUT_LINE('ID: ' || v_employee.id || ', Name: ' || v_employee.name);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。