添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
被表白的绿茶  ·  MT5 ...·  10 月前    · 
骑白马的烈马  ·  Jsp+Servlet ...·  2 年前    · 

Introduction

The ORA-01422 error in Oracle indicates that a query returned more rows than expected. This typically occurs when a SELECT INTO statement retrieves more than one row, but the expectation was to fetch exactly one row. Understanding the causes and learning how to resolve this error is crucial for maintaining smooth database operations.

Understanding the Cause

The ORA-01422 error occurs when:
  • Multiple Rows Returned: A SELECT INTO statement returns more than one row.
  • Incorrect Query Assumptions: The query assumes a unique result, but the actual data has multiple matching rows.
  • Data Inconsistency: The data might not be unique, leading to multiple rows being fetched.
  • Step-by-Step Solutions

    Here are several methods to resolve the ORA-01422 error:

    1. Use Aggregation Functions

    If you expect a single value from multiple rows, use aggregation functions like MAX , MIN , SUM , or AVG .

    BEGIN SELECT MAX(salary) INTO v_max_salary FROM employees WHERE department_id = 10;

    2. Use a CURSOR for Multiple Rows

    If you need to handle multiple rows, use a CURSOR to fetch each row individually.

    DECLARE CURSOR emp_cursor IS SELECT employee_id, first_name, last_name FROM employees WHERE department_id = 10; v_emp_id employees.employee_id%TYPE; v_first_name employees.first_name%TYPE; v_last_name employees.last_name%TYPE; BEGIN OPEN emp_cursor; FETCH emp_cursor INTO v_emp_id, v_first_name, v_last_name; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE(v_emp_id || ' ' || v_first_name || ' ' || v_last_name); END LOOP; CLOSE emp_cursor;

    3. Add Filtering Criteria

    Ensure your query is specific enough to return only one row by adding more conditions to your WHERE clause.

    BEGIN SELECT employee_id, first_name, last_name INTO v_emp_id, v_first_name, v_last_name FROM employees WHERE department_id = 10 AND ROWNUM = 1;

    4. Use SELECT INTO with EXCEPTION Handling

    Handle the situation where multiple rows are returned using the TOO_MANY_ROWS exception.

    BEGIN SELECT employee_id, first_name, last_name INTO v_emp_id, v_first_name, v_last_name FROM employees WHERE department_id = 10; EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE('Query returned more than one row.');

    Examples

    Example 1: Handling Multiple Rows with Aggregation

    If you want to fetch the highest salary from a department:

    BEGIN SELECT MAX(salary) INTO v_max_salary FROM employees WHERE department_id = 20;

    Example 2: Using CURSOR for Multiple Rows

    If you need to process all employees in a department:

    DECLARE CURSOR emp_cursor IS SELECT employee_id, first_name, last_name FROM employees WHERE department_id = 20; v_emp_id employees.employee_id%TYPE; v_first_name employees.first_name%TYPE; v_last_name employees.last_name%TYPE; BEGIN OPEN emp_cursor; FETCH emp_cursor INTO v_emp_id, v_first_name, v_last_name; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE(v_emp_id || ' ' || v_first_name || ' ' || v_last_name); END LOOP; CLOSE emp_cursor;

    Example 3: Using Specific Filtering Criteria

    If you want to ensure only one employee is returned:

    BEGIN SELECT employee_id, first_name, last_name INTO v_emp_id, v_first_name, v_last_name FROM employees WHERE department_id = 20 AND ROWNUM = 1;

    Example 4: Using SELECT INTO with Exception Handling

    Handling cases where the query might return multiple rows:

    BEGIN SELECT employee_id, first_name, last_name INTO v_emp_id, v_first_name, v_last_name FROM employees WHERE department_id = 20; EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE('Query returned more than one row.');

    Conclusion

    The ORA-01422 error in Oracle is encountered when a query returns more rows than expected. By understanding its causes and applying the appropriate solutions, database administrators and developers can effectively manage and prevent this error. Regularly reviewing query criteria, using CURSOR for multiple rows, and incorporating exception handling are essential practices to maintain smooth database operations.

    Related content

  • How to Resolve ORA-01031: Insufficient Privileges
  • Resolving ORA-01034: Oracle Not Available
  • How to Resolve ORA-01403: No Data Found
  • ORA-01422: Exact Fetch Returns More Rows Than Requested
  • Resolving ORA-01461: Can Bind a LONG Value Only for Insert into a LONG Column
  • ORA-01555 Snapshot Too Old
  • ORA-01722: Invalid Number
  • Resolving ORA-01830: Date Format Picture Ends Before Converting Entire Input String
  • Resolving ORA-03113 End-of-File on Communication Channel
  • How to Resolve ORA-04030: Out of Process Memory
  • ORA-04031: Unable to Allocate X Bytes of Shared Memory
  • Resolving ORA-06508: PL/SQL: Could Not Find Program Unit Being Called
  • Resolving ORA-20000: Buffer Overflow
  • Resolving ORA-20001: Maximum Web Service Requests Exceeded
  • Resolving ORA-27101: Shared Memory Realm Does Not Exist
  • Resolving ORA-3135: Connection Lost Contact
  • Database Growth Calculator
    Plan DB growth and storage needs now!
  • RAID Storage Calculator
    RAID, performance, and redundancy!
  • Database Backup Size Calculator
    Instantly calculate database backup size!
  • Base64 Encoder & Decoder
    Encode or decode Base64 text and files!
  • SQL Beautifier | SQL Formatter
    Beautify SQL with syntax highlights!
  • Unix Timestamp Conversion
    Convert Unix time to human-readable date
  • Cron Job Generator
    Online Cron Job Generator for Unix scheduling
  • IP Subnet Calculator
    IP Subnet Calculator for IPv4/IPv6 ranges
  • Network Latency Test Tool
    Measure network latency - Speed & Stability
  • Bandwidth Calculator
    Calculate website bandwidth and data speeds
  • Encode and Decode URL Online
    Quickly encode or decode URLs online
  • Online Word Counter
    Count words, characters, and keyword density
  • Unit Conversion Calculator
    Convert units like length, weight, and temperature
  • Random Password Generator
    Generate strong, unique passwords for security
  • Password Strength Checker
    Check password strength and improve protection

  • Read more | Learn more

    Cloud Technology

  • Software as a Service (SaaS)
    Understanding SaaS
  • Platform as a Service (PaaS)
    Understanding PaaS
  • Infrastructure as a Service (IaaS)
    Understanding IaaS
  • Understanding Private Cloud
    Private Cloud Insights
  • Understanding Hybrid Cloud
    Hybrid Cloud Insights
  • Understanding Kubernetes | K8s
    Kubernetes Overview
  • Kubernetes Commands for Beginners
    Essential K8s Commands
  • Kubernetes Best Practices
    Optimizing K8s Deployment
  • Managing Kubernetes
    K8s Cluster Management
  • CI/CD Pipeline
    Automating Development Workflows
  • AWS Security Groups
    Understanding Stateful Security
  • Microservices | Stateful vs Stateless
    Comparing Stateful and Stateless
  • Cloud Data Protection
    Securing Cloud Data

  • Read more | Learn more

    Oracle Database

  • How to install Oracle 21c on Linux?
    Step-by-Step guide for Oracle 21c installation
  • How to Install Oracle 19c on Linux?
    Step-by-Step guide for Oracle 19c installation
  • Automating Database Startup and Shutdown
    Using systemd to manage Oracle Database
  • How to Configure DataGuard in Oracle
    DataGuard configuration step-by-step
  • Oracle AWR Report
    Understanding Oracle AWR reports
  • SQL AWR Reports
    Understanding SQL AWR reports in Oracle
  • Oracle Explain Plan | Execution Plans
    Understand Oracle execution plans
  • Identifying Top Current SQL Queries
    SQL queries consuming time in Oracle
  • How to Identify and Troubleshoot Deadlocks
    Resolving Oracle deadlock issues
  • Identifying Historically Expensive SQLs
    Optimize expensive queries in Oracle
  • Identifying Top Current SQL Queries
    Fix time-consuming SQL queries in Oracle
  • Dynamic CPU Scaling | Resource Manager
    Managing CPU resources in Oracle
  • How to Configure Huge Pages in Oracle
    Setting up huge pages in Oracle
  • Checking Tablespace Usage in Oracle
    Monitor and manage tablespace usage
  • Oracle 19c Flashback Database
    Learn Oracle 19c flashback feature
  • Oracle Data Pump - expdp and impdp
    Learn Oracle Data Pump commands
  • How to Resolve ORA-01403: No Data Found
    Fix the ORA-01403 error in Oracle
  • ORA-12537: TNS: Connection Closed
    Fix TNS connection closed errors
  • ORA-20001: Maximum Web Service Requests
    Fix the ORA-20001 error in Oracle
  • Resolving ORA-3135: Connection Lost
    Fix the ORA-3135 connection error

  • Read more | Learn more

    MSSQL Database

  • Optimizing SQL Server on VMware
    Best practices for SQL Server
  • SQL Server TempDB Best Practices
    Best practices for TempDB performance
  • Updating Database Statistics in SQL
    Update SQL Server statistics
  • SQL Query to Find Unused Indexes
    Find unused indexes in SQL Server
  • How to get SQL Server config details
    Retrieve SQL Server config info
  • How to find Missing Indexes
    Find missing indexes in SQL Server
  • How to find table and index stats
    Find table & index stats in SQL Server
  • Sessions Blocking chain tree
    View blocking chain sessions
  • Identifying Blocking Sessions
    Locking & blocking sessions
  • Identifying Locked Rows in Tables
    Locked rows in SQL Server
  • Identifying Current session Locks
    Identify current session locks
  • Index Usage Statistics
    Understand index usage stats
  • Monitoring Application Sessions
    Monitor sessions with T-SQL
  • Exploring Database with T-SQL
    Explore SQL Server database
  • SQL Server query plan cache
    Query plan cache in SQL Server
  • Database I/O Latency
    Analyze I/O latency
  • Managing Index Fragmentation
    Handle index fragmentation
  • Managing Fragmented Tables
    Handle fragmented tables
  • Understanding Lock Escalations
    Lock escalation management
  • Identifying Top Wait Events
    Top SQL wait events

  • Read more | Learn more

    PostGres Database

  • PostgreSQL Anonymizer: Data Masking
    Data masking in PostgreSQL
  • How to Install PostgreSQL on Linux?
    Install PostgreSQL on RedHat Linux
  • Handful PostgreSQL Commands
    Commonly used PostgreSQL commands
  • How to Restart the PostgreSQL Service
    Restart PostgreSQL service on Linux
  • How to Install Extensions in PostgreSQL?
    Install PostgreSQL extensions
  • Generating a UUID in PostgreSQL
    Create a UUID in PostgreSQL
  • Postgres Host Authentication Methods
    Understand Postgres auth methods
  • Understanding pg_catalog Schema
    Understand pg_catalog schema in PostgreSQL
  • Troubleshooting Blocked Queries
    Fix long-running or blocked queries
  • Analyze Postgres Performance with Logging
    Logging activity & pgBadger for performance
  • Optimizing PostgreSQL: Shared Buffers
    Tuning shared buffers for PostgreSQL
  • PostgreSQL Vacuuming Best Practices
    Best practices for vacuuming in PostgreSQL
  • Analyzing and Vacuuming Tables in Postgres
    Vacuum and analyze tables in PostgreSQL
  • Best Practices for Managing Postgres Stats
    Manage PostgreSQL statistics effectively
  • Tracking SQL Statements with pg_stat
    Track SQL statements in PostgreSQL
  • pg_hint_plan: Control Execution Plans
    Control execution plans in PostgreSQL
  • Understanding PostgreSQL Cache Hit Ratio
    Analyze PostgreSQL cache hit ratio
  • Resolving Password Authentication Failed
    Fix password authentication issues
  • Resolving FATAL: Database does not exist
    Fix database not found error
  • Understanding and Analyzing Index Usage
    Analyze index usage in PostgreSQL

  • Read more | Learn more

    Linux

  • How to Configure Swap Space in Linux?
    How to configure swap space in Linux
  • How to Install Oracle VirtualBox on Windows
    How to install Oracle VirtualBox on Windows
  • Installing RHEL Linux 9 on a Virtual Machine
    How to install RHEL Linux 9 on VM
  • How to Change Hostname in Linux?
    How to change the hostname in Linux
  • How to Configure an Offline YUM Repository?
    How to set up offline YUM repo in RHEL 9
  • How to Set Up the X Display in Linux?
    How to set up X display in Linux
  • Adding a New Disk to VM in Linux?
    How to add new disk to Linux VM
  • How to Install Linux 8 on a VM?
    How to install Linux 8 on VM

  • Read more | Learn more

    ASP/C#

  • How to Encrypt a Connection String in .NET
    Secure web.config connection string
  • Resolving 'ConfigProtectionProvider' Error
    Fix 'ConfigProtectionProvider is Not Allowed' error
  • How to Secure Session Variables in .NET
    Secure session variables in ASP.NET
  • Logging Event Auditing Information in .NET
    Log events and audits in ASP.NET
  • Implementing a Simple CAPTCHA in .NET
    Add CAPTCHA to forms in ASP.NET

  • Read more | Learn more

    Online Tests

  • Oracle Proficiency Test
    Over 100+ Questions & Answers for Oracle
  • SQL Server Proficiency Test
    Over 100+ Questions & Answers for SQL Server
  • PostGreSQL Proficiency Test
    Over 90+ Questions & Answers for PostgreSQL
  • Linux Proficiency Test
    Over 100+ Questions & Answers for Linux
  • Basic MSSQL Objective Questions
    Basic MSSQL Assessments for Beginners
  • Advanced MSSQL Objective Questions
    Level 2 MSSQL Objective Assessments
  • Expert MSSQL Objective Questions
    Level 3 MSSQL Objective Assessments
  • Basic Postgres Objective Questions
    Basic PostgreSQL Assessments for Beginners
  • Advanced Postgres Objective Questions
    Level 2 PostgreSQL Objective Assessments
  • Expert Postgres Objective Questions
    Level 3 PostgreSQL Objective Assessments

  • Read more | Learn more