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?
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With