Automated Date

0

I have the following question: How to put an automatic date in SQL Server or in C #?

For example in this query :

SELECT id,Registration FROM tbl_CRs
WHERE Registration BETWEEN '20170201' AND '20170216'
and [Status]='OPEN'

In C # it would be something like this:

string query = "SELECT id,Registration FROM tbl_CRs WHERE Registration BETWEEN '" + LblMes.Text + "' and '"+LblHoy.Text+"' ";

As you may have noticed, I put today's date, it makes a comparison of the first day of this month, but when it is March, I want you to make a comparison of the first day of March, and so on. I want the first parameter I declare in the where to be changed to the first day of the future months.

    
asked by CarlosR93 16.02.2017 в 19:52
source

3 answers

1

I understand that what you ask is to make a query that brings values between the first day of the current month and the current date. For SQL it would look like this:

SELECT Id, Registration 
FROM tbl_CRs
WHERE Registration BETWEEN DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) AND GETDATE()
AND [Status] = 'OPEN'

For C # it would be:

using (SqlConnection conn = new SqlConnection(ConnectionString))
{
    string query = "SELECT Id, Registration FROM tbl_CRs WHERE Registration BETWEEN @PrimerDiaMes AND @FechaActual";
    SqlCommand cmd = new SqlCommand(query, conn);
    cmd.Parameters.Add("@PrimerDiaMes", new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1));
    cmd.Parameters.Add("@FechaActual", DateTime.Now);
    conn.Open();
    var result = cmd.ExecuteReader();
    while (result.Read())
    {
        //Código con el resultado obtenido
    }
    conn.Close();
}

I recommend you stop using the dynamic queries setup (as you put it in your example), it is susceptible to SQL Injection, here the official documentation for the best practices in this regard.

    
answered by 16.02.2017 / 22:24
source
1

You can also do it directly from an SQL statement:

"SELECT id,Registration FROM tbl_CRs WHERE Registration BETWEEN DATEADD(month, DATEDIFF(month, 0, getdate()), 0) and convert(date,getdate())"

Take into consideration that in the way you could be doing it, it would cause sql injection problems.

    
answered by 16.02.2017 в 20:42
0

Just today I face a problem similar to yours, the way I could solve it was the following:

c # already brings libraries for the time so I use them and assign them to a variable of type string.

string FechaInicial = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd");

This brings me the result as it accepts the date of sql (year-month-day)

and for the final date use:

string FechaFinal= DateTime.Today.ToString();

and already arms the query that in your case would be:

string query = "SELECT id,Registration FROM tbl_CRs WHERE Registration BETWEEN '" + FechaIncial+ "' and '"+FechaFinal+"' ";

I hope you serve the explanation :) Greetings!.

    
answered by 17.02.2017 в 02:44