0

I tried comparing using the below codes but it failed to work. Did I do the wrong way to compare datetime? The data type in my sql table is datetime for both Premium_StartDate and Premium_EndDate. Please help, thanks

SqlCommand cmd = new SqlCommand("SELECT * FROM UserPremiumPeriod WHERE Premium_Username = '" + Session["username"] + "' AND Premium_StartDate <= '" + DateTime.Now + "' AND Premium_EndDate >= '" + DateTime.Now + "' ", con);
anonymous
  • 19
  • 2
  • Do you get an error? Which one? Maybe you need to [format DateTime](https://stackoverflow.com/q/17418258/1997232) so that your sql server able to understand it? – Sinatr Feb 03 '21 at 13:13
  • 2
    `'" + Session["username"] + "'`. Do not do that. https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection And do the same for the dates - don't pass them as strings - pass them as parameters. – mjwills Feb 03 '21 at 13:14
  • @mjwills then how i do so? – anonymous Feb 03 '21 at 13:16
  • @Sinatr Most people who suggest SQL Server date formats neglect to test with servers where the date format is YDM. Hilarity often ensues. – mjwills Feb 03 '21 at 13:17
  • `then how i do so?` Did you read the link? – mjwills Feb 03 '21 at 13:17
  • @mjwills, dates or similar things don't pose much of threat. Though I agree on consistancy to use params. And it may actually solve OP issue. – Sinatr Feb 03 '21 at 13:18
  • @Sinatr `dates or similar things don't pose much of threat.` Many people suggest date formats (like YYYY/MM/DD) that don't work reliably. So it is a threat in the sense of "it doesn't necessarily work". `And it may actually solve OP issue.` It will _definitely_ solve it. – mjwills Feb 03 '21 at 13:20
  • @mjwills yes i did, but how do I compare more or less than? – anonymous Feb 03 '21 at 13:27
  • 1
    `SELECT * FROM UserPremiumPeriod WHERE Premium_Username = @Username AND Premium_StartDate <= @Now AND Premium_EndDate >= @Now` is the SQL. The duplicate shows you how to pass the two parameters needed. – mjwills Feb 03 '21 at 13:28
  • @mjwills i think it worked, thank you ! – anonymous Feb 03 '21 at 13:45

0 Answers0