February 2, 2010 at 7:50 am
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
February 2, 2010 at 8:11 am
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
February 2, 2010 at 9:59 am
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
February 2, 2010 at 10:04 am
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
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply