我正在寻找一种方法,可以在创建新凭证项目的新数据库表行之前检查我的凭证项目的 DiscountCode 值是否存在。我以前尝试过自己用几种方法来做,但它们对我不起作用,而且我是学习 ASP.NET 和 C# 的新手。
如何在创建新行之前检查并确保 DiscountCode 不存在于数据库表中?
这是我想出的创建新数据库行的代码。
public int VoucherInsert()
{
int result = 0;
string queryStr = "INSERT INTO Voucher(VoucherName,VoucherDescription,DiscountAmount,DiscountCode)" + " values (@Name,@Description,@Amount,@Code)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("@Name", this.Name);
cmd.Parameters.AddWithValue("@Description", this.Description);
cmd.Parameters.AddWithValue("@Amount", this.Amount);
cmd.Parameters.AddWithValue("@Code", this.Code);
conn.Open();
result += cmd.ExecuteNonQuery();
conn.Close();
return result;
}