Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Oracle binding variables with LIKE in C#

As part of an effort to stop using dynamic SQL generation and encourage use of bind variables, I am running into some problems.

I am querying an Oracle 9i database from an ASP.NET page using Oracle Data Providers for .NET

The query is

sql = "SELECT somedata FROM sometable WHERE machine = :machineName ";

I define the Oracle Parameter as follows

OracleParameter parameter = new OracleParameter();
parameter.ParameterName = "machineName";
parameter.OracleDbType = OracleDbType.Varchar2;
parameter.Value = machine; //machine is a variable of type string
parameterList.Add(parameter);

This works fine for "=" operator. But I just can't seem to get it to work with "LIKE". I don't know how to format the query so that it accepts usage of the "%" wildcard.

I have tried:

sql = "SELECT somedata FROM sometable WHERE machine LIKE :machineName% ";
sql = "SELECT somedata FROM sometable WHERE machine LIKE ':machineName%' ";
sql = "SELECT somedata FROM sometable WHERE machine LIKE :machineName||% ";

and also:

parameter.Value = machine+'%';

but all I get are ORA-00911 (illegal character) and ORA-01036 (illegal name/value) exceptions.

What am I doing wrong?

like image 895
PJ. Avatar asked Sep 24 '10 19:09

PJ.


2 Answers

Try:

sql = "SELECT somedata FROM sometable WHERE machine LIKE :machineName || '%' ";

Because of the BIND variable, there wouldn't need to be single quotes around it. But the % is not, so I would expect it needing to be encapsulated.

like image 191
OMG Ponies Avatar answered Sep 29 '22 00:09

OMG Ponies


Here is a full query example:

string commandText = "SELECT LastName, FirstName FROM PEOPLE WHERE UPPER(LastName) LIKE '%' || :lastName || '%' AND UPPER(FirstName) LIKE '%' || :firstName || '%'";

string oradb = "yourDatabaseConnectionStringHere"; // Might want to add Using statement for this code and try catch

OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand
{
     Connection = conn,
     CommandText = commandText,
     CommandType = CommandType.Text
};

/*IMPORTANT: adding parameters must be in order how they are in order in the SQL statement*/
cmd.Parameters.Add(new OracleParameter("lastName", model.LastName.Trim().ToUpper()));
cmd.Parameters.Add(new OracleParameter("firstName", model.FirstName.Trim().ToUpper()));

OracleDataReader dr = cmd.ExecuteReader();
like image 38
Dmitri K Avatar answered Sep 29 '22 00:09

Dmitri K