简体   繁体   English

检查条件C#后如何更新比较日期的db列

[英]How to update a db column comparing dates after checking a condition C#

I have a table column as status(Varchar,records "Paid"/"Unpaid" only) and another column as nextDateOfPay(datetime, records a date).I need to update this status column as Unpaid for the records which are as Paid when the date(present date) is passed the date in nextDateOdPay column.And I need to repeat this update for every row in the table. 我有一个表列作为状态(Varchar,仅记录“付费”/“未付费”)和另一列作为nextDateOfPay(日期时间,记录日期)。我需要将此状态列更新为未付的记录,这些记录为付费时日期(当前日期)在nextDateOdPay列中传递日期。我需要为表中的每一行重复此更新。 Primary key is Id column(integer). 主键是Id列(整数)。 I have no clue where to start,do i need to use T-sql or if i have to use sql agent job.I'd like to know if there is a simple solution that i can write in the program itself.Thank you so much in advance ! 我不知道从哪里开始,我是否需要使用T-sql或者如果我必须使用sql agent job。我想知道是否有一个简单的解决方案,我可以在程序本身写。谢谢你提前多了! Code so far is as, 到目前为止的代码是,

dateTimePicker3.Value = DateTime.Now;
textBox12.Enabled = false;
string newstat;
string query = "select Id,nextDateOfPay from gymTb where status='Paid'";

SqlConnection cn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(query, cn);

DateTime x = DateTime.Now;
DateTime y;

if (cn.State.ToString() == "Closed")
{
    cn.Open();
}
try        
{
    object dtx = cmd.ExecuteScalar();
    y = Convert.ToDateTime(dtx);
    int result = DateTime.Compare(x, y);

    if (result >= 0)
        newstat = "Unpaid";
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

A simple UPDATE query would do: 一个简单的UPDATE查询可以:

UPDATE gymTb SET status='Unpaid'
WHERE status='Paid' AND nextDateOfPay <= getdate()

You could call this from your application, triggered by manually pressing a button or perhaps using timer logic. 您可以从应用程序中调用此方法,通过手动按下按钮或使用计时器逻辑触发。

To make it run daily, and independent from your application, you can put the UPDATE statement in a recurring job in SQL Server Agent. 要使其每天运行并独立于您的应用程序,您可以将UPDATE语句放在SQL Server代理中的定期作业中。 For more on that see here: 有关详细信息,请参阅此处:
how to schedule a job for sql query to run daily? 如何安排sql查询的作业每天运行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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