开发者

c# asp.net problem with 'must declare the scalar variable'

开发者 https://www.devze.com 2022-12-24 00:36 出处:网络
I\'m currently making a front end to display license information for my companies software audit but im no pro with sql or asp.net so iv ran into a bit of trouble. I\'m trying to get a sum of how many

I'm currently making a front end to display license information for my companies software audit but im no pro with sql or asp.net so iv ran into a bit of trouble. I'm trying to get a sum of how many licenses there are across several rows so i can put it in a text box, but im getting the error 'Must declare the scalar variable "@softwareID".'

SqlConnection con1 = Connect.GetSQLConnection(); 
        string dataEntry = softwareInputTxt.Text; 
        string result; 

        dataEntry = dataEntry + "%"; 
con1.Open(); 
    开发者_如何转开发    SqlCommand Mycmd1; 
        Mycmd1 = new SqlCommand("select sum(license_quantity_owned) from licenses where software_ID like @softwareID", con1); 
        MyCmd.Parameters.AddWithValue("@softwareID", dataEntry); 
        result = (string)Mycmd1.ExecuteScalar(); 
        licenseOwnedTxt.Text = result; 

Could anyone point me in the right direction?


d'oh! Found it:

Mycmd1 ...
MyCmd ...

Two different commands!!!

You want:

Mycmd1.Parameters.AddWithValue("@softwareID", dataEntry);

(or assign MyCmd and Mycmd1 to be the same thing)


I think it might already be the default, but you could try setting the .CommandType to CommandType.Text explicitly. Also, note that AddWithValue can cause more query-plans than necessary to be created; I would explicitly create the variable with a known size (the size of the column plus spare for the %). The existing string-concat should already ensure it isn't null (which is usually the problem).

Additionally, note that both SqlConnection and SqlCommand are IDisposable - both could be wrapped in using here.

0

精彩评论

暂无评论...
验证码 换一张
取 消