How to create a function that takes a table name and where clause as parameters

  • Hello Everybody,

    I need to create a function in Oracle that takes the table name and where clause as parameters and returns the number of rows that satisfy this condition. Need this urgently. Any help most welcome.

    Thanks,

    Rasmi

  • In SQL you have to use dynamic sql and the EXEC(EXECUTE) statement.

    Oracle is the same, but you would use EXECUTE IMMEDIATE,

    ie execute immediate 'drop table TEMPTBL';

    it sounds like you are trying to create a procedure to do all your adhoc sql statements; you should not do that. it's bad practice, and leaves you open to SQL injection, as well as potentially poor performance because no plan will get cached.

    if you have the table name and the WHERE statement, why not just do the ad hoc query directly from your application? why send it off to a proceudre?

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • Hello ,

    Thanks for the very fast reply. I am actually studying in uni and am doing this for an assignment 😀

    I am trying to use the execute immediate but its still giving an error. If someone can tell me whats wrong in this function it would be really helpful.

    CREATE OR REPLACE FUNCTION fun_sel_test (tab1 IN VARCHAR2,p_where IN VARCHAR2)

    RETURN NUMBER

    IS

    l_count NUMBER(20);

    BEGIN

    EXECUTE IMMEDIATE

    'SELECT COUNT(*) FROM' || tab1 ||

    'WHERE' || p_where;

    RETURN l_count;

    END;

    /

    Thanks,

    Rasmi

  • look at the error you are getting; it should be very obvious;

    if i used your function for a table named "Customers" and a WHERE statement that was "CustomerName LIKE 'c%'

    what would your statment look like?

    SELECT COUNT(*) FROMCustomersWHERECustomerName LIKE 'c%'

    does that help you identify the problem?

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply