17

作为停止使用动态 SQL 生成并鼓励使用绑定变量的努力的一部分,我遇到了一些问题。

我正在使用 Oracle Data Providers for .NET 从 ASP.NET 页面查询 Oracle 9i 数据库

查询是

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

我将 Oracle 参数定义如下

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

这适用于“=”运算符。但我似乎无法让它与“LIKE”一起使用。我不知道如何格式化查询,以便它接受“%”通配符的使用。

我试过了:

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||% ";

并且:

parameter.Value = machine+'%';

但我得到的只是 ORA-00911(非法字符)和 ORA-01036(非法名称/值)异常。

我究竟做错了什么?

4

2 回答 2

33

尝试:

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

由于 BIND 变量,不需要在其周围加上单引号。但是 % 不是,所以我希望它需要被封装。

于 2010-09-24T19:48:08.607 回答
0

这是一个完整的查询示例:

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();
于 2021-04-23T16:37:51.423 回答