1

I am looking for a way to check if the DiscountCode value of my voucher item exists before creating a new database table row of the new voucher item. I've tried doing it with a few ways on my own previously but they didn't work for me and I am new to learning ASP.NET and C#.

How can I check and make sure the DiscountCode does not exist in the database table before creating a new row?

Here are the codes to create a new database row I have came up with.

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;
        }
Kah Hao
  • 11
  • 2
  • 2
    `IF NOT EXISTS ( SELECT 1 FROM ... WHERE ) INSERT INTO...`. – Dai Jan 09 '21 at 12:16
  • What do you want to do if it does exists - update or discard? – P.Salmon Jan 09 '21 at 12:18
  • I want to discard it. Basically nothing will happen if it already exists. – Kah Hao Jan 09 '21 at 12:20
  • Here is a [discussion about "insert if not exists"](https://stackoverflow.com/questions/1361340/how-to-insert-if-not-exists-in-mysql) you can refer to. – Kyle Wang - MSFT Jan 11 '21 at 01:57
  • create a function , may be call as public int VoucherSelect(string InputParameter) , that trigger TSQL "select * from Voucher where DiscountCode='InputParameter' " , and check return query row count. if row return = 0 , then proceed your function VoucherInsert() else display error message to your fount end. – HO LI Pin Jan 11 '21 at 08:58

0 Answers0