Search code examples
oracleado.netoracle12cdatareader

Why does this ADO.NET query return no results?


I have the following code that executes a SQL statement and looks for a result.

var sql = @"select BOQ_IMPORT_ID "
          + "from ITIS_PRJ.PRJ_BOQ_IMPORT_HEADER "
          + "where PROJECT_ID = :Projectid "
          + "order by CREATED_ON desc "
          + "fetch first 1 row only";
using (var conn = new OracleConnection(ApplicationSettings.ConnectionString))
using (var cmd = new OracleCommand(sql, conn))
{
    conn.Open();
    cmd.Parameters.Add(LocalCreateParameterRaw("ProjectId", projectId));
    var reader = cmd.ExecuteReader();
    if (reader.Read())
    {
        byte[] buffer = new byte[16];
        reader.GetBytes(0, 0, buffer, 0, 16);
        var boqId = new Guid(buffer);
        return boqId;
    }

    return null;
}

Where LocalCreateParameterRaw is declared as:

public static OracleParameter LocalCreateParameterRaw(string name, object value)
{
    OracleParameter oracleParameter = new OracleParameter();
    oracleParameter.ParameterName = name;
    oracleParameter.OracleDbType = OracleDbType.Raw;
    oracleParameter.Size = 16;
    oracleParameter.Value = value;
    return oracleParameter;
}

The underlying type for 'projectId' is 'Guid'.

The if (reader.Read()) always evaluates to false, despite there being exactly one row in the table. It normally should return only one row.

Using GI Oracle Profiler I can catch the SQL sent to the db, but only once did the profiler provide a value for the :ProjectId parameter, and it was in lower case. Like that it returned no results, but as soon as I applied UPPER to that value, I get a result.

It looks like I somehow have to get my parameter into uppercase for the query to work, but I have no idea how. Yet if I do a ToString().ToUpper() on the projectId GUID, I get a parameter binding error.

VERY IMPORTANT: I have tried removing the where clause altogether, and no longer add a parameter, so all rows in the table should be returned, yet still no results.


Solution

  • I don't know how, but making the SQL string a verbatim string (prefixed with @) causes the proc to work. So, it doesn't work with:

    var sql = @"SELECT BOQ_IMPORT_ID "
          + "FROM ITIS_PRJ.PRJ_BOQ_IMPORT_HEADER "
          + "WHERE PROJECT_ID = :projectid "
          + "ORDER BY CREATED_ON DESC "
          + "FETCH FIRST ROW ONLY";
    

    Yet the same command string in SQL Developer executes and returns results. When I make my SQL string verbatim, as below, I get results.

    var sql = @"select BOQ_IMPORT_ID 
                from ITIS_PRJ.PRJ_BOQ_IMPORT_HEADER 
                where PROJECT_ID = :ProjectId 
                order by CREATED_ON desc 
                fetch first 1 row only";