views:

65

answers:

3

I'm trying to implement a simple search, using LIKE in my SQL statement:

        Using cmd As New OracleCommand
           cmd.Connection = conn
           cmd.CommandType = CommandType.Text
           cmd.CommandText = "select * from TABLE where FIELD like '%:text%'"
           cmd.Parameters.AddWithValue("text", searchValue)
           ...
        End Using

This doesn't work - what is the best way to parameterize the search value?

+3  A: 

update: my bad, if you are using oracle driver, see this link for help. this depends on which driver you use for db access, in case of oledb you need to do following here is corrected code:


Using cmd As New OracleCommand
           cmd.Connection = conn
           cmd.CommandType = CommandType.Text
           cmd.CommandText = "select * from TABLE where FIELD like ?"
           cmd.Parameters.AddWithValue("@text", '%'+searchValue+'%')
           ...
        End Using

in case of oracle driver you need to do following:


Using cmd As New OracleCommand
           cmd.Connection = conn
           cmd.CommandType = CommandType.Text
           cmd.CommandText = "select * from TABLE where FIELD like :text"
           cmd.Parameters.AddWithValue(":text", '%'+searchValue+'%')
           ...
        End Using

lakhlaniprashant.blogspot.com
That results in an error - I don't think you can concat strings with + in oracle.
chris
no problem, please provide error, and i will try to fix it.
lakhlaniprashant.blogspot.com
Ken Bloom's answer provides the answer - `||` is the concatenation operator in Oracle. There's also the `CONCAT()`-function, but it'll result in less legible SQL.
Cthulhu
+8  A: 
select * from TABLE where FIELD like ('%' || :text || '%')
Ken Bloom
+1  A: 

In cases like this I prefer this syntax:

select * from TABLE where INSTR(FIELD, :text) > 0
Jeffrey Kemp
People have forgotten all about `INSTR` these days, for a few reasons: (a) familiarity with C, which uses different function names, (b) familiarity with OO languages, which just let you call `find` on the object you're searching (no need to have the type name in the function name), (c) familiarity with scripting languages which use regular expressions for their string manipulation. Not that you're answer's wrong, it's just that people don't think of it anymore.
Ken Bloom
I started using it this way after seeing it by Oracle Apex in its auto-generated code.
Jeffrey Kemp