Use query parameters with an ODBC connection to an iSeries AS400 database in .NET?

StackOverflow https://stackoverflow.com/questions/22210862

  •  09-06-2023
  •  | 
  •  

Pergunta

If I understand this link correctly, I should be able to pass query parameter values to my ODBC command and have it execute successfully. It doesn't, so here's my problem code:

OdbcConnection myConnection = new OdbcConnection("DSN=myODBCConnection");

myConnection.Open();

OdbcCommand myCommand = myConnection.CreateCommand();

myCommand.CommandText = "SELECT * FROM MyTable FETCH FIRST ? ROWS ONLY";
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.AddWithValue("P1", 5);

OdbcDataReader myDataReader;

// Fails here! It doesn't recognize P1 as a parameter to pass in for ?.
myDataReader = myCommand.ExecuteReader();

The code should select the first 5 rows from MyTable. Instead, it throws this error:

System.Data.Odbc.OdbcException: ERROR [42000] [IBM][System i Access ODBC Driver][DB2 for i5/OS]SQL0104 - Token ? was not valid. Valid tokens: ROW ROWS.

Thanks for anyone who'd like to help! And yes, if I execute a parameterless query, it works fine.

Foi útil?

Solução

Apparently you cannot parametrize FETCH FIRST ROWS as discussed under Paramertize Fetch First n Rows Only in DB2 you can either put it direct in the sql string or use a different strategy.

don't know how to change a comment to answer

Outras dicas

AFAIK, parameter markers are allowed where the resulting data type can be determined, e.g., where a column-definition is available. See Table 1. under the PREPARE statement for a list of allowed marker locations and how to specify markers at those locations.

Since there is no "column" to which the value must be compatible, there has been no development done to give this (a 'fetch first' marker) any meaning to DB2. Also, since OLAP specifications can be used to provide ROW_NUMBER(), there probably isn't much demand to put development effort into a probably less useful element of queries. (As noted earlier, the FETCH FIRST clause is generally intended more for performance rather than strict results, though it does actually limit number of rows available in the result set.)

If FETCH FIRST is required for some reason, you'll need to use a dynamic statement.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top