Read and insert data into a table via C #

-3

I have this code to insert values into a column of a table:

        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 inserting, I need to read this column and see if there is any equal. 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!

    
asked by anonymous 02.05.2017 / 11:50

1 answer

1

You can solve 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 have helped.

    
02.05.2017 / 13:51