必须声明标量变量异常

时间:2013-08-13 07:31:16

标签: sql c#-4.0

我正在使用:

string insertQ = "insert into Customer(Name, CNIC, Address, Balance) values(@name, @cnic, @address, @balance); SELECT CAST(scope_identity() AS int);";

SqlCommand insertCmd1 = new SqlCommand(insertQ, con);

Int32 newId = (Int32)insertCmd1.ExecuteScalar();

但是

  

“必须声明标量变量”

异常发生在ExecuteScalar

请告诉我如何解决它......

1 个答案:

答案 0 :(得分:5)

您需要传递参数值:

string insertQ = "insert into Customer(Name, CNIC, Address, Balance) values(@name, @cnic, @address, @balance); SELECT CAST(scope_identity() AS int);";

SqlCommand insertCmd1 = new SqlCommand(insertQ, con); 
insertCmd.Parameters.Add("name", SqlDbType.VarChar).Value = "name";     
insertCmd.Parameters.Add("cnic", SqlDbType.VarChar).Value = "cnic"; 
insertCmd.Parameters.Add("address", SqlDbType.VarChar).Value = "address";     
insertCmd.Parameters.Add("balance", SqlDbType.VarChar).Value = "balance"; 


Int32 newId = (Int32)insertCmd1.ExecuteScalar();

SqlDbType必须符合您的计划。