Reputation: 5397
When I attempt to execute the following non query sql command in my application I always get the error message -
Must declare the scalar variable '@RateID'
I'm a bit at a loss as to why I receive this error. Here is my code:
string sqlText = "INSERT INTO tblRates (RateID, IPName, RateName, Rate, DateFrom, DateTo, Active) " +
"VALUES (@RateID, @IPName, @RateName, @Rate, @DateFrom, @DateTo, @Active);";
SqlCommand sqlCom = new SqlCommand(sqlText);
sqlCom.Parameters.Add("@RateID", SqlDbType.Int);
sqlCom.Parameters.Add("@IPName", SqlDbType.Text);
sqlCom.Parameters.Add("@RateName", SqlDbType.Text);
sqlCom.Parameters.Add("@Rate", SqlDbType.Decimal);
sqlCom.Parameters.Add("@DateFrom", SqlDbType.Date);
sqlCom.Parameters.Add("@DateTo", SqlDbType.Date);
sqlCom.Parameters.Add("@Active", SqlDbType.Bit);
this._rateID = NextID();
sqlCom.Parameters["@RateID"].Value = this._rateID;
if (this._ipName == "All")
{
sqlCom.Parameters["@IPName"].Value = DBNull.Value;
}
else
{
sqlCom.Parameters["@IPName"].Value = this._ipName;
}
sqlCom.Parameters["@RateName"].Value = this._rateName;
sqlCom.Parameters["@Rate"].Value = this._rate;
sqlCom.Parameters["@DateFrom"].Value = this._dateFrom;
sqlCom.Parameters["@DateTo"].Value = this._dateTo;
this._active = true;
sqlCom.Parameters["@Active"].Value = this._active;
cSqlQuery cQ = new cSqlQuery(sqlText, "non query");
When I step through line by line, I see the parameter @RateID
is successfully added to the sqlCommand
object, the method NextID
correctly returns an integer value which is accepted as the Value
of the @RateID
parameter, but when I execute non query on the SqlCommand
I get the aforementioned error.
Any help much be much appreciated.
Upvotes: 4
Views: 7154
Reputation: 1275
You seem to be passing sqlText to your cSqlQuery object, but I believe you need to pass the command (sqlCom).
I don't know exactly how the cSqlQuery works, but passing the sqlText is no good.
Upvotes: 0
Reputation: 754220
You're setting up the sqlCom
object - and the code looks fine.
But then: it seems you're just executing the SQL command here:
cSqlQuery cQ = new cSqlQuery(sqlText, "non query");
not using all that setup code you had before! Why?
The parameters and all are contained in the sqlCom
object - but your cSqlQuery
doesn't seem to actually look at that object - just the SQL statement itself...
What happens if you use this line instead:
sqlCom.ExecuteNonQuery();
Does this work without exception?
Upvotes: 6