How to make a select that brings the data registered in a given week?

Asked

Viewed 65 times

2

I intend to list all the data registered in a given week, someone can help me?

I did something similar to the example below and it doesn’t work.

public List<View_Venda> Venda_Semanais()
{
    List<View_Venda> lis = new List<View_Venda>();
    SqlConnection conexao = new SqlConnection(caminho);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conexao;
    cmd.CommandType = CommandType.Text;
    string lista = "select *from view_venda where data_registo=@data_registo <= DateTime.Now Add Day(-7) And DateTime.Today";
    cmd.CommandText = lista;
    cmd.Parameters.AddWithValue("@data_registo", DateTime.Today);
    conexao.Close();
    SqlDataReader dr;
    conexao.Open();
    dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        View_Venda obj = new View_Venda();
        obj.id_venda = Convert.ToInt32(dr["id_venda"].ToString());
        obj.funcionario = dr["funcionario"].ToString();
        obj.fundo_inicial = Convert.ToDecimal(dr["fundo_inicial"].ToString());
        obj.total_veda_caixa = Convert.ToDecimal(dr["total_veda_caixa"].ToString());
        obj.total_venda_multicaixa = Convert.ToDecimal(dr["total_venda_multicaixa"].ToString());
        obj.total_multipagamento = Convert.ToDecimal(dr["total_multipagamento"].ToString());
        obj.caixa_final = Convert.ToDecimal(dr["caixa_final"].ToString());
        obj.conciliacao = Convert.ToDecimal(dr["conciliacao"].ToString());
        obj.data_registo = Convert.ToDateTime(dr["data_registo"].ToString());
        lis.Add(obj);
    }
    return lis;
}
  • does not return anything or triggers exception at some point? You can format the code using the editor options. (=

  • This way will also generate error

1 answer

2

Have in your *Sqlcommand * Two parameters, one for the start date and one for the end date,(put in the example as A and B respectively), The string of the command was also incorrect, the dates you were trying to pass should be inserted in the parameters as below

string lista = "select * from view_venda where data_registo >= @data_registoA and  data_registo<=@data_registoB";
    cmd.CommandText = lista;
    cmd.Parameters.AddWithValue("@data_registoA", DateTime.Today.AddDays(-7));
    cmd.Parameters.AddWithValue("@data_registoB", DateTime.Today);
  • This way will generate error, in my view there is no attribute with name data_registoA and B.

  • data_registoaA and B are only named parameters passed pro select. This will be replaced by values passed in the method AddWithValue

  • These 'attributes' are parameters, are only the values that will be replaced and passed to the database, in case it would replace to "data_record >= '06/04/2017' and data_record<='13/04/2017' "

Browser other questions tagged

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