日期:2014-05-19  浏览次数:20718 次

给SQL语句传入参数出错
源代码如下:
OleDbConnection   dbConn   =   new   OleDbConnection(@ "Provider=IBMDADB2.1;Data   Source=ENTLOGIC;Persist   Security   Info=True;Password=entlogic;User   ID=entlogic ");
OleDbCommand   dbCmd   =   new   OleDbCommand( "SELECT   *   FROM   CC_TASK_BASE   WHERE   RECEIVEDEPT=@UserName ",   dbConn);
dbCmd.Parameters.Add( "@UserName ",   OleDbType.VarChar);
dbCmd.Parameters[ "@UserName "].Value   =   "9989 ";
dbConn.Open();
OleDbDataReader   dr   =   dbCmd.ExecuteReader();

执行到最后一句代码就会出错,提示:
[DB2/NT]   SQL0206N     "@USERNAME "   在使用它的上下文中无效。     SQLSTATE=42703

请问这是怎么回事啊?

------解决方案--------------------
看不出啥错,不知道和DB2数据库有没关系
改成下面的看看:
OleDbCommand dbCmd = new OleDbCommand(String.Format( "SELECT * FROM CC_TASK_BASE WHERE RECEIVEDEPT={0} ", "9989 "), dbConn);
//dbCmd.Parameters.Add( "@UserName ", OleDbType.VarChar);
//dbCmd.Parameters[ "@UserName "].Value = "9989 ";
dbConn.Open();
------解决方案--------------------
你用的DB2吧...
你换成SQL SERVER 看看,你的代码没错
------解决方案--------------------
用的DB2,用?替代参数

OleDbConnection dbConn = new OleDbConnection(@ "Provider=IBMDADB2.1;Data Source=ENTLOGIC;Persist Security Info=True;Password=entlogic;User ID=entlogic ");
OleDbCommand dbCmd = new OleDbCommand( "SELECT * FROM CC_TASK_BASE WHERE RECEIVEDEPT = ? ", dbConn);
dbCmd.Parameters.Add( "? ", OleDbType.VarChar).Value = "9989 ";
dbConn.Open();
OleDbDataReader dr = dbCmd.ExecuteReader();