Hi, I'm working in C# and SQL Server. I was wondering how to validate the last input record of a worker with the following instruction:
SqlCommand cmd = new SqlCommand("select CAST( max(registroEntrada )as date) as registroEntrada FROM usuarios WHERE numTrabajador = '"+txtTrabajador.Text+"'", conexion);
where I want to evaluate if the day of his last registration corresponds to the same day that he wants to register with:
var dias = DateTime.Now.ToString("yyyy-MM-dd");
Doing some research I found that when using ExecuteScalar I could save the date in a variable and to be able to compare it as follows:
if(resultado.ToString() == dias)
{
MessageBox.Show("Verifica que tengas una entrada activa.");
}
else
{
MessageBox.Show("Entrada activa.");
}
When I enter a valid number when evaluating, it sends me directly to the if block, even though I have a response with valid sql data, but if I change as follows
if(resultado.ToString() != dias)
{
MessageBox.Show("Entrada activa.");
}
else
{
MessageBox.Show("Verifica que tengas una entrada activa.");
}
It enters the if block even though it doesn't have an active input, I don't know what the error could be since everything returns null
When you compare dates you must do it with the type
date
on both sides of the equality, otherwise, if you comparestring
you will get a lot of trouble, and more dealing with occasional valuesnull
.That said, I think the simplest thing is to delegate the validation to the sql statement, comparing the date of the last entry with today's date:
If the
int
result ofExecuteScalar
is zero, it means that there is no record for today, otherwise there is.