ORACLE: Considerations for passing in parameter variable names when writing a function

Source: Internet
Author: User

When developers in Oracle write their own SQL functions, the entry parameter name should not be the same as the field name of the table in the SELECT statement. Otherwise, although the compilation succeeds, the running result is often incorrect.

Example:

 1 CREATE OR REPLACE FUNCTION S_GET_EMP_NAME(EMPNO nvarchar2) return nvarchar2 is 2   ENAME nvarchar2(100); 3 begin 4   SELECT E.ENAME 5     INTO ENAME 6     FROM EMP E 7    WHERE E.EMPNO = EMPNO 8      AND ROWNUM = 1; 9   RETURN ENAME;10 end;

The code is very simple. Get the employee name ename through employee ID empno.

The test code is as follows:

Select s_get_emp_name (7654) from dual;

Returned result: Smith

But this is not the expected value. The data in EMP is as follows:

Select empno, ename from EMP;

----------------------------------------------------

7369 Smith
7499 Allen
7521 ward
7566 Jones
7654 Martin
7698 Blake
7782 Clark
7788 Scott
7839 king
7844 Turner
7876 Adams
7900 James
7902 Ford
7934 Miller

----------------------------------------------------

Apparently, 7654 does not correspond to Smith. What is the problem?

WhereE. empno = empno

In this row of conditions, because the variable name empno is the same as the field empno In the table, when executing the SQL statement, it is considered that the column empno is compared with itself, so it is always true, in the end, only rownum = 1 is used, and only the first row is returned.

 

Solution:

Rename the entry parameter in the function. For example, add the prefix "in _" to "in_empno ".

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.