You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Oracle 11g插入内置departments表时触发ORA-00001: unique constraint (HR.DEPT_ID_PK) violated错误的求助

解决ORA-00001: unique constraint (HR.DEPT_ID_PK) violated错误

Hey there, let's break down this error you're hitting. The ORA-00001 means you're trying to insert a row with a department_id that already exists in the HR.departments table—since DEPT_ID_PK is the primary key on that column, duplicates aren't allowed.

First, let's confirm the root cause by checking if department ID 70 is already present:

SELECT department_id, department_name 
FROM HR.departments 
WHERE department_id = 70;

If this returns a row, that's exactly why your insert is failing (the sample HR schema in Oracle 11g actually has a pre-populated "Public Relations" department with ID 70 by default!).

可行的解决选项

  • 选项1:使用一个未被占用的部门ID
    先查询当前表中最大的部门ID,确保你选的ID是唯一的:

    SELECT MAX(department_id) FROM HR.departments;
    

    然后用一个比最大值更大的ID来执行插入,比如:

    INSERT INTO HR.departments(department_id, department_name, manager_id, location_id) 
    VALUES (280, 'Public Relations', 100, 1700);
    

    (注:默认HR schema的部门ID通常到270,所以280大概率是安全的,但还是建议先用max查询确认)

  • 选项2:如果是想更新现有部门信息,改用UPDATE语句
    如果你本来就想修改ID为70的部门信息,而不是新增,就用更新语句:

    UPDATE HR.departments
    SET department_name = 'Public Relations', manager_id = 100, location_id = 1700
    WHERE department_id = 70;
    

    记得如果你的会话不是自动提交模式,执行完后要运行COMMIT;提交更改。

  • 选项3:删除并重建主键约束(不推荐)
    除非你有特殊业务需求允许部门ID重复,否则不要这么做——内置HR schema的DEPT_ID_PK是用来保证部门唯一性的核心约束,随意修改会破坏数据完整性。

内容的提问来源于stack exchange,提问作者Mohammad Junaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:57:32