tags:

views:

91

answers:

3

I need to compare the value of a column (LASTNAME) with a system variable (:VARIABLE), but the variable is an email address, so I need to trim off the "@email.com" and "firstname." Some things I've tried:

select * 
  from TABLENAME 
 where LASTNAME LIKE :VARIABLE

select * 
  from TABLENAME 
 where LASTNAME IN :VARIABLE

I've been able to trim off the @email.com, can't figure out how to trim off FIRSTNAME. at the same time.

A: 

You can use a combination of SUBSTR and INSTR.

The instr function returns the location of a substring in a string. With this one you can locate the "."or the "@" char.

Then use the substr to get the substring from the begining to the previous located position

SELECT SUBSTR('Take the first four characters', 1, 4)

Jonathan
+2  A: 

Regular expressions can help:

SQL> SELECT LTRIM(regexp_substr('[email protected]','\.[^@]*'),'.') last_name from dual;

LAST_NAME
---------
lastname

Your query could then look like:

SELECT *
  FROM tablename 
 WHERE UPPER(LTRIM(regexp_substr(:VARIABLE,'\.[^@]*'),'.')) = UPPER(lastname);
DCookie
Regex support is Oracle 10g+, right?
OMG Ponies
Yep 10g+ for regexp. And be sure to get your DBA to sign off on it, since new features tend to be where Oracle bugs pop up, at least that is what our DBA always reminds us of when we want to try something new and fancy.
Dougman
10g is hardly "new".
DCookie
@DCookie: True, but most DBA's (and organizations) tend to be extremely cautious, especially within large apps. Lots of Oracle 8 and 9i still running wild out there. We tend to stay about a full major rev behind and our DBA is pretty progressive.
Dougman
While 10g is not new, we don't know what version the OP is using. It's not my attitude, but I admit I've had similar experiences to Dougman's about using syntax/functionality that is new to someone else who may have more social-political power.
OMG Ponies
This worked perfectly! THANK YOU!! btw, using Oracle Database 11g Enterprise Edition Release 11.1.0.7.0
Simpson
+1  A: 

Use:

SELECT t.*
  FROM TABLE t
 WHERE t.lastname LIKE '%' || SUBSTR(:VARIABLE, 
                                     INSTR(:VARIABLE, '.') +1, 
                                     INSTR(:VARIABLE, '@')) || '%'

Add UPPER or LOWER to both sides if you need to be sure of case insensitive matching.

Reference:

OMG Ponies