我有一个工作单系统,当我创建新的工作单时,我有以下几列订单日期,订单状态(打开或关闭),预期天数列(例如5天)以完成此订单,而我有实际天数列此列的实际天数默认值= 0。
我需要创建触发器以在打开工作订单时每隔一天自动将列实际天数的值每天增加1。
当新的一天从午夜12点开始时,该如何触发每日增量并更新值?
我正在使用SQL SERVER。
这是我的桌子:
CREATE TABLE [Documents_followup](
[Doc_id] [int] IDENTITY(1,1) NOT NULL,
[Document_subject] [nvarchar](200) NULL,
[Date] [datetime] NULL,
[Document_number] [nvarchar](50) NULL,
[Doc_place_id] [int] NULL,
[Doc_expect_time] [int] NULL,
[Doc_finish_time] [int] NULL,
[DocStatus_id] [int] NULL,
[Notes] [nvarchar](100) NULL,
[user_id] [int] NULL)
答案 0 :(得分:0)
您不需要触发器,只需添加一个计算列即可。我只会使用datediff
函数。
select
*,
actual_days = datediff(day,order_date,getdate())
from YourTable
现在,这对于仅打开职位的工作不起作用,但是您无法考虑何时关闭工作。我想这就是actual_days
要做的事情...添加到order_date
来确定它何时关闭。取而代之的是,我将摆脱actual_days
列,而只添加一个close_date
列,只要order_status
从打开更改为关闭就可以更新。然后,您可以使用相同的datediff
逻辑。
这比编写每天更新表的工作更有意义。如果没有触发 TRIGGER
的内容,更新将不会发生。此外,执行此RBAR会很慢,因此,如果您确实无法更改设计,则只需使用SQL Agent Job即可批量执行此操作。
update yourtable
set actual_days = datediff(day,order_date,getdate())
where order_status = 'open
您可以将其安排为每天运行或执行任何操作...但是,再次提醒您,如果在运行之后直到第二天运行,作业都关闭了,这将是不准确的。
另一种选择是,一旦订单关闭,仅更新actual_days
。这样一来,您就可以使用触发器,或者仅将其包括在update statement
中,例如,用于关闭机票的样板。
create proc usp_closeTicket (@order_no int)
as
update mytable
set
order_status = 'closed'
,actual_days = datediff(day,order_date,getdate())
where order_no = @order_no
当然,您需要使用适当的错误处理,而不能使用。 Check our Erland's blog for that.
修改,现在您已经添加了DDL
没有什么比我上面的建议有所不同。主要是我将使用UPDATE
语句而不是触发器,该触发器将使用您的列名更改为此:
create proc usp_closeTicket (@order_no int)
as
update Documents_followup
set
DocStatus_id = 1 --or what ever signifies closed
,Doc_finish_time= datediff(day,[Date],getdate())
where Doc_id = @order_no