如何将数据库中的“ EndDate”与今天的当前日期进行比较?

时间:2019-02-01 09:30:51

标签: c# asp.net sql-server

我想根据EndDate是否是<今天的日期来执行查询。这是我到目前为止所拥有的,我需要知道如何进行比较谢谢!

//Delete from DB Condition (EndDate)
        if (sqlCon.State == ConnectionState.Closed)
            sqlCon.Open();
        
        SqlCommand sqlCmd = new SqlCommand("DeleteByDate", sqlCon);
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.ExecuteNonQuery();
        sqlCon.Close();
        Clear();

这是存储过程。

ALTER PROC [dbo].[DeleteByDate]
@AdvID int
AS
BEGIN
    UPDATE a SET a.Status = 0
    FROM Advertisement a
    WHERE a.AdvID = @AdvID
END

1 个答案:

答案 0 :(得分:0)

您可以像这样通过C#或SQL处理它:

C#

if(EndDate < DateTime.Now.Date)     // Assuming EndDate is already defined in your class 
{
    using(SqlConnection sqlCon = new SqlConnection(sqlCon.ConnectionString) )
    using(SqlCommand sqlCmd = new SqlCommand("DeleteByDate", sqlCon))
    {
        sqlCon.Open();
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Parameters.Add("@AdvID", SqlDbType.Int);
        sqlCmd.Parameters["@AdvID"].Value = AdvID //Assuming it's already defined;
        sqlCmd.ExecuteNonQuery();   
    }   
}

SQL:

ALTER PROC [dbo].[DeleteByDate]
@AdvID int
AS
BEGIN

    DECLARE @CurrentDate DATE = GETDATE() -- to get current date

    -- Assuming that Advertisement table has the column EndDate
    IF EXISTS (SELECT * FROM Advertisement a WHERE a.EndDate < @CurrentDate )
    BEGIN 
        UPDATE a SET a.Status = 0
        FROM Advertisement a
        WHERE a.AdvID = @AdvID  
    END 
END

如果使用C#,它将直到满足条件时才触发sp,但是在SQL中,它将使C#触发sp,并且每次代码运行时,sp​​都会检查条件。

因此,这取决于您的应用程序结构,是首先运行应用程序,还是首先运行数据库,这是您要走的路。