带日期参数的删除触发器的SQL Server语法

时间:2018-12-19 09:48:49

标签: sql-server

我需要在Microsoft SQL Server中为DELETE操作创建触发器,以便 如果列“到期日期”>“ sysdate”,则无法删除表中的第一行。

表格示例:

| Warranty | Expiry Date      |
+----------+------------------+
| product  | 19 - DEC - 2020  |

1 个答案:

答案 0 :(得分:0)

create table dbo.t (Warranty varchar(100), Expiry_Date date);
insert into dbo.t values 
('product', '20201219'),
('product 2015', '20151219');
 go

 create trigger tr_selective_delete on dbo.t instead of delete
 as
    set nocount on;
    delete t
    from dbo.t t
         join deleted d
            on t.Warranty = d.Warranty
    where t.Expiry_Date <= getdate();

delete dbo.t;

select *
from dbo.t;
----
--product   2020-12-19

请注意,联接字段(在您的情况下为Warranty)应为unique