How to create C# method to do 2 Query SQL Insert?

Asked

Viewed 340 times

0

To create a c# method to insert data, this method does more than one INSERT behind the other?

'Cause I tried it here and it didn’t work out!

  • 2

    Yes you can, post what you did so we can try to help you.

  • I am in the busão, but, my idea was to create two variables in the method and assign query’s in these variables and then activate the method with some button in win Forms just this

1 answer

1

Good morning,

I did it this way and it worked out for me.

Following example:

    public static void InsereDadosArqTxtRetSaidaDAL(out string pstrMsg, out bool pbooRetorno, ArrayList parrHeaderArqTxt, List<ArrayList> plstItensArqTxt)
    {
        pstrMsg = string.Empty;
        pbooRetorno = false;

        SqlConnection conn = ConexaoBD.CriarConexao();

        // Inseri dados na tabela de cabeçalho
        using (SqlCommand cmd = new SqlCommand("uspCtzInsertConfirmPedProcess", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@cd_rejeicao", parrHeaderArqTxt[1]));
            cmd.Parameters.Add(new SqlParameter("@nu_ped", parrHeaderArqTxt[2]));
            cmd.Parameters.Add(new SqlParameter("@dt_hrs_inclusao", parrHeaderArqTxt[3]));

            SqlParameter nuRetornoID = cmd.Parameters.Add(new SqlParameter("@cd_confirmPedProcess", SqlDbType.Int));
            nuRetornoID.Direction = ParameterDirection.Output;

            SqlTransaction tran = cmd.Connection.BeginTransaction();
            cmd.Transaction = tran;

            try
            {
                cmd.ExecuteNonQuery();

                // Capturando o último ID de retorno do parâmetro OUTPUT
                int nuCdPedProcess = (int)nuRetornoID.Value;

                using (SqlCommand cmd2 = new SqlCommand("uspCtzInsertConfirmItPedProcess", conn))
                {
                    cmd2.CommandType = CommandType.StoredProcedure;

                    cmd2.Transaction = tran;

                    foreach (ArrayList itensArqTxt in plstItensArqTxt)
                    {
                        cmd2.Parameters.Add(new SqlParameter("@cd_PedProcess", nuCdPedProcess));
                        cmd2.Parameters.Add(new SqlParameter("@cd_rejeicao", itensArqTxt[1]));
                        cmd2.Parameters.Add(new SqlParameter("@cd_mercadoria", itensArqTxt[2]));
                        cmd2.Parameters.Add(new SqlParameter("@qtde_mercadoria_ped", itensArqTxt[3]));
                        cmd2.Parameters.Add(new SqlParameter("@qtde_mercadoria_ok", itensArqTxt[4]));

                        cmd2.ExecuteNonQuery();

                        cmd2.Parameters.Clear();
                    }
                }
                tran.Commit();

                pbooRetorno = true;
            }
            catch (SqlException ex)
            {
                tran.Rollback();

                pstrMsg = string.Format("Erro:\nMétodo: 'InsereDadosArqTxtRetSaidaDAL'\nDetalhes: {0}", ex.Message);

                pbooRetorno = false;
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
    }
  • 1

    what happens if this method is called thousands of times and an error occurs in the cmd.Connection.BeginTransaction?

  • I think it could be a mistake. From what I understood, I would have to open the transaction inside the Try block, if the error occurs the catch block makes the necessary treatment ?

  • The best thing would be to put everything inside one using (var tran = new TransactionScope), do not open the connection inside the CriarConexao(), let the caller method decide the best time to open the connection and finally, install it using a using: using (var conn = ConexaoBD.CriarConexao())

  • Toby in case the form of implementation will change correct ? Because I’m running the test and I’m starting to get some syntax errors, I checked msdn on this link: https://msdn.microsoft.com/pt-br/library/system.transactions.transactionscope%28v=vs.110%29.aspx? f=255&Mspperror=-2147217396, and saw that I have to change the structure of the method is just that ?

  • an example (not tested): http://codepaste.net/e915p9

  • Toby, I implemented the example I haven’t been able to test yet, but I saw that there are adjustments in the code I believe this way will get better. But I have doubts about the transaction rollback in case there are any mistakes. The block itself using (var Tran = new Transactionscope()) already makes this treatment automatically, or in case I would have to follow your tip that is in the catch block and, let the error go up and treat it off ? And the issue of true or false Return, the method does not accept because it was declared void. I would have to switch to bool or continue passing an output parameter as before ?

  • Diego, my fault, I forgot to change the signature of the method to return a Boolean. Transactionscope will give a Rollback if Complete is not called, that is, exited the transaction using and did not have Complete, then an automatic Rollback is made.

  • Ball show, as soon as I have a txt in the client’s FTP, I download and test the method and ti give a feedback. Thanks for the tips.

Show 3 more comments

Browser other questions tagged

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