How to know a row's value before its inserted

2019-07-30 15:04发布

问题:

I have this query:

SELECT COUNT(date) FROM patients WHERE date= 2012/02/23

If that COUNT returns 10, there will be an alert that tells to the user that it cannot accept more visit. How do i validate that? How can i know that? In php i just have to do this:

<?php

$QUERY = "SELECT COUNT(date) AS count_results FROM patients WHERE date= 2012/02/23";
$execute_query = $CONEXION ->prepare($query);
$execute_query->execute();
$results = execute_query->fetch(PDO::FETCH_ASSOC);

if(results['count_results ']==10)
{
echo "Cannot accept know visit.";
}else{
echo "Ok";
}
?>

But i have no idea of how to do that in ASP.NET C#. Help??

回答1:

Perform a check in the page_load event, if you are validating the logged in user. Or if you need to validate depending on a user value that you are attempting to insert, use the button_click event for record being inserted.

SqlCommand cmdEvent = new SqlCommand("SELECT COUNT(date) FROM patients WHERE date= '2012/02/23'", yourSqlConnection);
object myCount;
if (yourSqlConnection.State == ConnectionState.Closed){ yourSqlConnection.Open(); }
myCount = cmdEvent.ExecuteScalar();
if (yourSqlConnection.State == ConnectionState.Open){ yourSqlConnection.Close(); }

if (myCount != null)
{
  if ((int)myCount >= 10)
  {
    // Logic here e.g myLabel.Text = "You have reached your maximum of 10 visits!";
    return;
  }
}