为什么我会收到ORA-01438错误

时间:2014-01-09 17:29:43

标签: java sql oracle jdbc casting

我有一个EMPLOYEE表,其中包含列(主键)EMPLOYEE_ID NUMBER(6)

以下方法检查表中是否存在员工记录

public boolean exists(int employeeId) {

        Connection con = ConnectionManager.getConnection();
        boolean exists = false;
        String stmt = "select EMPLOYEE_ID , FIRST_NAME , LAST_NAME , EMAIL , PHONE_NUMBER ,"
                + "HIRE_DATE , JOB_ID , SALARY , COMMISSION_PCT , MANAGER_ID , DEPARTMENT_ID "
                + " FROM EMPLOYEES where cast (EMPLOYEE_ID as Number(2)) = ?";
        PreparedStatement pstmt = null;
        try {
            pstmt = con.prepareStatement(stmt);
            pstmt.setInt(1, employeeId);
            pstmt.execute(); //Returns true if the first object that the query returns is a ResultSet object
            exists = pstmt.getResultSet().next();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                pstmt.close();
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return exists;
    }

现在,在SQL语句中,当我使用cast (EMPLOYEE_ID as Number(2)) = ?并使用输入2 exists调用employeeOperations.exists(2);方法时,我收到以下错误

ORA-01438: value larger than specified precision allowed for this column

为什么会发生此错误,即使列的大小足够大?

适用于4位或更多位数的输入(表中存在的employee_id的最大长度为4),即cast (EMPLOYEE_ID as Number(4)) = ?有效。

1 个答案:

答案 0 :(得分:2)

NUMBER(6)投射到NUMBER(2)时,EMPLOYEE_ID大于99的记录会导致错误(例如,Oracle无法将100放入\d{2} )。

快速修复,请使用此请求:

SELECT COUNT(1) FROM EMPLOYEES WHERE EMPLOYEE_ID = ?