How to insert an "if" into an INSERT string in the database?

Asked

Viewed 66 times

-1

I have the following variable

 DateTime ContaRecebeDataPagto = Convert.ToDateTime(dgOrigem.SelectedRows[0].Cells[2].Value.ToString());

She gets a value from DataGrid, in some cases the date of payment, and in other cases has nothing as it has no payment.

And I got the following INSERT that I do with the result of DataGridView:

//INSERT TABELA DESTINO
                string sqlIncluir = "INSERT INTO CONTARECEBER (" +
                    "CLIENTE," +
                    "VENCIMENTO," +
                    "DATAPAGAMENTO," + .........
                    ") Values(" +
                    "\'" + "," + "\'" + ContaReceCliente +         //CLIENTE
                    "\'" + "," + "\'" + ContaReceVencimento +//  + //VENCIMENTO
                    "\'" + "," + "\'" + ContaRecebeDataPagto.ToString("dd.MM.yyyy")+ ........  +//DATAPAGTO

On the line where ContaRecebeDataPagto, would have to have a if guy se != de vazio puxar, senão colocar null, and continue with the other information.

How can I do that?

  • Not directly related, but: Do not concatenate variables directly into the query, as this leaves the code vulnerable to SQL Injection attacks. Learn more by reading here: https://answall.com/q/100729/112052

1 answer

0

You can use a ternary operator to not have to create more lines

 DateTime ContaRecebeDataPagto = dgOrigem.SelectedRows[0].Cells[2].Value == null ? null : Convert.ToDateTime(dgOrigem.SelectedRows[0].Cells[2].Value.ToString())

How to read a ternary operation:

ContaRecebeDataPagto == null test to see if the variable is null

? null the value after the query will be the value returned if the condition is true

: Convert.ToDateTime(dgOrigem.SelectedRows[0].Cells[2].Value.ToString()) the value after two points is what will be returned if the condition is false

Basically is a one-line if, ie:

ContaRecebeDataPagto == null ? null : ContaRecebeDataPagto.ToString("dd.MM.yyyy")

It’s the same thing as doing the following (Which is also an alternative):

if(dgOrigem.SelectedRows[0].Cells[2].Value == null)
    ContaRecebeDataPagto = null
else
    ContaRecebeDataPagto = Convert.ToDateTime(dgOrigem.SelectedRows[0].Cells[2].Value.ToString())

If what you want to do is do this test on the string, it’s very simple too, just add the operator on the line you need the test:

"\'" + "," + "\'" + ContaRecebeDataPagto == null ? "" : ContaRecebeDataPagto.ToString("dd.MM.yyyy")+ ........  +//DATAPAGTO

Following the same logic if the variable ContaRecebeDataPagto is null, an empty string will be inserted (""). If not, the date will normally be entered.

  • 1

    thanks Vitor, thanks I’ll test here and warn you

Browser other questions tagged

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