简体   繁体   中英

C# SQL Select Query table parameter

I am trying to select from a table where the table name is being assigned from a variable as im using two different tables. However it comes up with a DB2Exception Error.

db2Error = {"ERROR [42601] [IBM][AS] SQL0104N  An unexpected token \"'TABLENAME'\" was found following \"\". 

This query is the one which causes the error - Table name is a string which has the names of the table.

string strUpdate = "SELECT COMMENT FROM '" + tableName + "' WHERE NUMBER = '" + strNumber + "' AND CODE = '" + c.Trim() + "' ";

This query works fine though -

 //  string strUpdate = "SELECT COMMENT FROM TABLE WHERE NUMBER = '" + strNumber + "' AND CODE = '" + c.Trim() + "'";

Is it possible to parametrise/use variable for the table name?

Why are you using qoutes in your from statement? it should just simply be

select sysdate 
from dual;

Also use the SqlCommand class to add parameters in your selectstatement as follows.

string strUpdate = "SELECT COMMENT FROM @tablename WHERE NUMBER = @strnumber AND CODE = @c";
SqlCommand insertCommand = new SqlCommand(strUpdate , connection);
insertCommand.Parameters.AddWithValue("@tableName ", tableName );
insertCommand.Parameters.AddWithValue("@strNumber ", strNumber );
insertCommand.Parameters.AddWithValue("@c", c.trim());

SQL injection risk aside, the two shown queries are simply not the same .

The query you showed is

string strUpdate = "SELECT COMMENT FROM TABLE WHERE NUMBER = " etc.

However, the code you showed produces the following query:

string strUpdate = "SELECT COMMENT FROM 'TABLE' WHERE NUMBER = " etc.

The table name should simply not be in quotes. And given the fact you're not using parameters, this isn't even the parameter system's fault; the quotes are right there in your own query-constructing code. Just delete them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM