【问题标题】:Automatically update boolean property which is depend of date (MSSQL)自动更新依赖于日期的布尔属性 (MSSQL)
【发布时间】:2021-02-20 08:51:56
【问题描述】:

我正在寻找自动更新表中布尔列的解决方案。此字段为“WarrantyActive”。我有另一列“保修日期”-> 保修期限。 我想创建函数:if (WarrantyDate 将 WarrantyActive 更改为 false。

    public bool WarrantyIsActive { get; set; }

    public DateTime WarrantyDate { get; set; }

当我使用表的 HttpGet 时,我应该在代码中执行此操作并检查此内容吗?或者在 MSSQL 中有没有更好的方法来自动检查这个值?

【问题讨论】:

    标签: c# sql-server rest model-view-controller automapper


    【解决方案1】:

    isWarrantyActive 应该是计算属性或计算列。

    作为计算属性:

    public class Product
    {
        public DateTime WarrantyDate { get; set; }
        public bool IsWarrantyActive => WarrantyDate >= DateTime.Now;
    }
    

    作为表格中的计算列:

    CREATE TABLE products 
    (
        product_id int NOT NULL PRIMARY KEY,
        warranty_date datetime NOT NULL,
        is_warranty_active AS (CAST(CASE WHEN warranty_date >= GETDATE() THEN 1 ELSE 0 END AS bit))
    )
    

    或者可以在查询中计算:

    SELECT 
        product_id, warranty_date, 
        (CAST(CASE WHEN warranty_date >= GETDATE() THEN 1 ELSE 0 END AS bit)) AS is_warranty_active
    FROM 
        products
    

    【讨论】:

      【解决方案2】:

      您可以像这样直接在属性上检查/设置:

      public bool WarrantyIsActive => WarrantyDate > DateTime.Now;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多