Search code examples
c#sqlms-accessoledbdatareaderoledbexception

"Syntax error in FROM clause" using OleDb in C# but no error for same query in Access itself


When using the following SQL-statement within c#/OleDbCommand.ExecuteReader I get a syntax error in FROM-clause. Using exactly the same statement in MS Access directly works fine.

SELECT 
s.idShots, s.shotdata, c.[original], s.[hash], comp.idCompetitions, comp.competitionsname, sh.idShooters, sh.firstname, sh.lastname 
FROM (([Shots] s 
INNER JOIN [ShotsCertificate] c ON c.[uuid] = s.[uuid]) 
INNER JOIN [Competitions] comp ON comp.idCompetitions = s.fidCompetitions) 
INNER JOIN [Shooters] sh ON sh.idShooters = s.fidShooters ORDER BY s.idShots ASC

Within c#:

        OleDbCommand cmd2 = new OleDbCommand("", dbc);
        cmd2.CommandText = "SELECT s.idShots, s.shotdata, c.[original], s.[hash], comp.idCompetitions, comp.competitionsname, sh.idShooters, sh.firstname, sh.lastname FROM" +
            " (([Shots] s" +
            " INNER JOIN [ShotsCertificate] c ON c.[uuid] = s.[uuid])" +
            " INNER JOIN [Competitions] comp ON comp.idCompetitions = s.fidCompetitions)" +
            " INNER JOIN [Shooters] sh ON sh.idShooters = s.fidShooters" +
            " ORDER BY s.idShots ASC";

        log.Debug(cmd2.CommandText);
        OleDbDataReader r = cmd2.ExecuteReader();

The dbc connections works fine, it's used in some previous commands and everything works.

Thanks for your suggestions!


Solution

  • For the record, the issue was that COMP is included in the list of Access SQL Reserved Words, presumably as an abbreviation of COMPRESSION for Access DDL. Changing the table alias from comp to cmpt allowed the query to run successfully under System.Data.OleDb:

    sql = "SELECT s.idShots, s.shotdata, c.[original], s.[hash], cmpt.idCompetitions, cmpt.competitionsname, sh.idShooters, sh.firstname, sh.lastname FROM" +
        " (([Shots] s" +
        " INNER JOIN [ShotsCertificate] c ON c.[uuid] = s.[uuid])" +
        " INNER JOIN [Competitions] cmpt ON cmpt.idCompetitions = s.fidCompetitions)" +
        " INNER JOIN [Shooters] sh ON sh.idShooters = s.fidShooters" +
        " ORDER BY s.idShots ASC";