tags:

views:

24

answers:

1

Hello fellows, I want to make a generalized method to fetch sequences for my application (OLEDB asp.net DB2)

   var seqName="Table1";
   string query="SELECT NEXTVAL FOR SchemaName."+seqName+" as seqid FROM sysibm.sysdummy1";

                using (OleDbCommand myCommand=new OleDbCommand(query,myConnection))
                {

                    myConnection.Open();
                    result = Convert.ToInt32(myCommand.ExecuteScalar());
                }

Using this instead won't work

   var seqName="mySeq1";
   string query="SELECT NEXTVAL FOR SchemaName.? as seqid FROM sysibm.sysdummy1";

                using (OleDbCommand myCommand=new OleDbCommand(query,myConnection))
                {
                    myCommand.Parameters.Add(new OleDbParameter("TabName",seqName));
                    myConnection.Open();
                    result = Convert.ToInt32(myCommand.ExecuteScalar());
                }

It throws

   SQL0104: Token ? was not valid. Valid tokens: <IDENTIFIER>.
Cause . . . . . :   A syntax error was detected at token ?.  Token ? is

not a valid token. A partial list of valid tokens is . This list assumes that the statement is correct up to the token. The error may be earlier in the statement, but the syntax of the statement appears to be valid up to this point. Recovery . . . : Do one or more of the following and try the request again: -- Verify the SQL statement in the area of the token ?. Correct the statement. The error could be a missing comma or quotation mark, it could be a misspelled word, or it could be related to the order of clauses. -- If the error token is , correct the SQL statement because it does not end with a valid clause.

+1  A: 

You can't use a parameter to specify a table name in a query, you can only use parameters to specify acutal values.

Your need to change the table name in the query suggests that you have data in the table name, when the data should really be in the table instead. You might consider redesigning the database so that you have this data in a single table instead of having several tables with the same structure.

Guffa
Hi sorry for the typo I am fetching sequence and not tables. Corrected my post.
Popo
@Popo: The same goes for any identifier; you can't use parameters to specify identifiers, only values.
Guffa
Thank you Guffa, I think you are spot on about the identifiers and values. I changed my approach in selecting the sequence.
Popo