参数化查询'(@ Name nvarchar(4000),@ Address nvarchar(4000),@ CNIC nvarchar(400'需要参数'@Name',未提供

时间:2017-05-19 06:38:39

标签: c# sql-server ado.net

我想从Command.ExecuteScalar();函数中获取最后一个插入的ID,但Command.ExecuteNoneQuery();

是可以的

这是代码

string query = "insert into Staff (Name, Address, CNIC, Email, Phone, UserType) values (@Name, @Address, @CNIC, @Email, @Phone, @UserType);SELECT SCOPE_IDENTITY();";

SqlConnection con = DALHelper.GetConnection();
SqlCommand cmd1, cmd2;
cmd1 = new SqlCommand(query, con);

SqlTransaction transaction = null;

//cmd1.Parameters.Add(new SqlParameter("@Name", System.Data.SqlDbType.VarChar, 250) { Value = staff.Name });
cmd1.Parameters.Add(new SqlParameter("@Name", staff.Name));
cmd1.Parameters.Add(new SqlParameter("@Address", staff.Address));
cmd1.Parameters.Add(new SqlParameter("@CNIC", staff.CNIC));
//cmd1.Parameters.Add(new SqlParameter("@Email", staff.Email));
cmd1.Parameters.Add(new SqlParameter("@Phone", staff.Phone));
cmd1.Parameters.Add(new SqlParameter("@UserType", staff.Type));
//cmd1.CommandType = System.Data.CommandType.Text;
SqlParameter emailPara = cmd1.Parameters.AddWithValue("@Email", staff.Email);

if(emailPara == null)
{
    emailPara.Value = DBNull.Value;
}

try
{
    con.Open();
    transaction = con.BeginTransaction();
    cmd1.Transaction = transaction;

    var newID = cmd1.ExecuteScalar();
}

0 个答案:

没有答案