Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Like statement in Function

Status
Not open for further replies.

iaresean

Programmer
Mar 24, 2003
570
ZA
Hi all;

I am trying to creat a function that will search my zones table for any zone that contains the text I am passing to the function. I realise I have to use % as the wildcard before and after my variable, but I can't get the below to work. I have tried "WHERE zone LIKE ('%' + $1 + '%');" but that doesn't work. "WHERE zone LIKE $1;" works but that means it needs an exact match. I have just about no postgres experience. I downloaded the guide from the postgres site but I am struggling to find the solution to my problem.

Code:
CREATE OR REPLACE FUNCTION searchForDomain(TEXT)
    RETURNS SETOF TEXT AS
'
        SELECT zone
            FROM zones
             WHERE zone LIKE '%$1%';
'

Any help would be greatly appreciated.

Thanks.

Sean. [peace]
 
the problem is in that you should escepe the ' with one more ' ;-))

i.e. ''

CREATE OR REPLACE FUNCTION searchForDomain(TEXT)
RETURNS SETOF TEXT AS
'
SELECT zone
FROM zones
WHERE zone LIKE ''%$1%'';
'
 
Thanks for your helpful and quick response Ceco! :)

Although you helped me move forward it wasn't the complete solution. I also had to seperate the variables and concatenate them together. Otherwise the search wouldn't be performed properly, and would never return any matches. Here is the working solution to my problem:
Code:
CREATE OR REPLACE FUNCTION searchForDomain(TEXT)
    RETURNS SETOF TEXT AS
'
        SELECT zone
            FROM zones
             WHERE zone LIKE (''%'' || $1 || ''%'');
' LANGUAGE 'sql' SECURITY DEFINER;

Thanks once again;

Sean. [peace]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top