Search code examples
c#asp.netconnectionoledb

Binding parameters to OLEDB command throws error


I am using AS 400 OLEDB with .NET. It uses '?' instead of '@param to bind parameters with a command Now there is a situation where the command is like

SELECT ...
FROM
   (SELECT ... 
         ROW_NUMBER() OVER(ORDER BY ColumnName) as RowNum
    FROM Employees e
   ) as DerivedTableName
WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1

Now my command becomes

    SELECT ...
FROM
   (SELECT ... 
         ROW_NUMBER() OVER(ORDER BY ColumnName) as RowNum
    FROM Employees e
   ) as DerivedTableName
WHERE RowNum BETWEEN ? AND (? + ?) - 1

Now when I bind parameters like

myCommand.Parameters.Add(new OleDbParameter("?",startRowIndex));
myCommand.Parameters.Add(new OleDbParameter("?", startRowIndex));
myCommand.Parameters.Add(new OleDbParameter("?", MaximumRows));

It throws error

SQL0417: Combination of parameter markers not valid.
Cause . . . . . :   The statement string specified as the object of a PREPARE statement contains a predicate or expression where parameter markers have been used as operands of the same operator.  The following restrictions apply to the use of parameter markers: -- Both the operands in a predicate cannot be parameter markers. For example, specifying predicates of the form:    ? = ?      or    ? = ( SELECT ? FROM x ) are not valid. 

How do I bind parameters in this situation ? I want to avoid sql injection :)


Solution

  • Try changing the names of the parameters

    myCommand.Parameters.Add(new OleDbParameter("@startRowIndex",startRowIndex));
    myCommand.Parameters.Add(new OleDbParameter("@startRowIndex2", startRowIndex));
    myCommand.Parameters.Add(new OleDbParameter("@MaximumRows", MaximumRows));
    

    but leave the SQL as is.