Read and insert data into a table via C#

Asked

Viewed 782 times

-3

I have this code to insert values in a table column:

        conn.Open();
        comm.CommandText = @"INSERT INTO ArticleBarCode(Code, Code_Article, BarCode, CreatedBy, CreatedOn, ModifiedBy, ModifiedOn, IsDeleted)
                           VALUES (@code1, @codearticle, @barcode, 1, @date1, 1, @date1, 0)";
        comm.Parameters.AddWithValue("@code1", next);
        comm.Parameters.AddWithValue("@codearticle", code);
        comm.Parameters.AddWithValue("@barcode", numbercode);
        comm.Parameters.AddWithValue("@date1", DateTime.Now);
        comm.ExecuteNonQuery();
        conn.Close();

But before I put it in, I need to read that column and see if there’s one like it. If it does not exist, I want to insert, if it already exists, I DO NOT want to insert again, I want to move on. Does anyone know how to help me in this ? Urgent !

  • Why don’t you put a constraint of unique in the bank instead of validating in the hand?

  • 1

    Urgent? Urgent?

1 answer

1

You can resolve by changing your SQL by leaving your code as follows:

    conn.Open();
    comm.CommandText = @"
    IF(NOT EXISTS(SELECT 1 FROM ArticleBarCode WHERE Code = @code1))
    BEGIN
       INSERT INTO ArticleBarCode(
          Code, 
          Code_Article, 
          BarCode, 
          CreatedBy, 
          CreatedOn, 
          ModifiedBy, 
          ModifiedOn, 
          IsDeleted
       ) VALUES (
          @code1, 
          @codearticle, 
          @barcode, 
          1, 
          @date1, 
          1, 
          @date1, 
          0
       )
    END";
    comm.Parameters.AddWithValue("@code1", next);
    comm.Parameters.AddWithValue("@codearticle", code);
    comm.Parameters.AddWithValue("@barcode", numbercode);
    comm.Parameters.AddWithValue("@date1", DateTime.Now);
    comm.ExecuteNonQuery();
    conn.Close();

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.