简体   繁体   中英

How To write an SQL query to return all “historical records” for TODAY'S DATE (month and day) for EVERY YEAR in the DB?

I've been using Visual Studio, C#, and SQL Server for 8 months now and have created a very functional personal project as I've been learning. But, there one bit of functionality I want in my program that I cannot get to work--automatically, that is.

If I type THIS into the button click event, run the program, and click the History button, it works perfectly. All seven columns of information go to the datagridview perfectly.

SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM AllConcertList WHERE Date LIKE '%%%%-05-27' ORDER BY DATE DESC; ", conn);

However, what is not awesome is that I want to write the query so that I can push a button ("History") that will return information from MAY 27 (or whatever today's date actually is) of EVERY YEAR, and I just can't figure out how to do it. It is a "Happened On This Day In History" list.

Obviously, I need to keep SELECT * FROM AllConcertList WHERE Date ... Somehow I need to include GETDATE() otherwise how would the program know to start with 05-27? But then I feel I need to include DATEFROMPARTS because I only really want Month and Day to be static to whatever the actual date (today) is. It must be a subquery in there somehow.

You should be able to use with simple month() and day() functions based on whatever the system's GETDATE() value is. Is this what you are looking for?

select 
      ACL.* 
   from 
      AllConcertList ACL
   where 
          month( ACL.Date ) = month( getdate()) 
      and day( ACL.Date ) = day( getdate())
   order by
      ACL.Date desc

No Parameters, no sql-injection

You can dynamically get today's month and date, then build your query string.

DateTime today = DateTime.Today;
String sql = String.Format("SELECT * FROM AllConcertList WHERE Date LIKE '%%%%-{0}' ORDER BY DATE DESC;", today.ToString("MM-dd"));
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);

And to show best practice, the same query, but parameterized.

DateTime today = DateTime.Today;
SqlCommand cmd =  new SqlCommand("SELECT * FROM AllConcertList WHERE Date LIKE @monthDate ORDER BY DATE DESC;", conn);
cmd.Parameters.AddWithValue("@monthDate", "%%%%-" + today.ToString("MM-dd"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM