简体   繁体   English

SQL触发器更新/插入

[英]SQL Trigger update/Insert

I'm creating a table and setting up a trigger to insert/update field_3 using field_1 and 2. See my example below. 我正在创建一个表并设置触发器以使用field_1和2插入/更新field_3。请参见下面的示例。

ID | Start_Date | End_Date | Period |
1    3/10/17      3/20/17      10
2    2/05/17      3/10/17       5 

Trigger 触发

ALTER TRIGGER [dbo].[tr_insert_Period]
  ON  [dbo].[MEDICAL_EXCUSE]
  for update
AS 
BEGIN

  SET NOCOUNT ON;

declare @Start_Date Datetime
declare @End_Date  Datetime
declare @Period Float

set @Start_Date = ( select me_start_date from inserted)
set @End_Date = ( select ME_End_Date from inserted)
set @Period  = ( select Period  from inserted)

update MEDICAL_EXCUSE
set @Period  = DATEDIFF(day,@Start_Date , @End_Date)

END

it won't trigger just work if you execute Manually. 如果您手动执行,它不会触发工作。

Any help Much Appreciated. 任何帮助,不胜感激。

Don't use a trigger. 不要使用触发器。 Just use a computed column. 只需使用计算列即可。 I think this is what you want: 我认为这是您想要的:

alter table KOPS_MEDICAL_EXCUSE
    add period as (DATEDIFF(day, me_start_date, me_end_date));

Note that datediff() returns an integer, so there is no reason to declare anything as a float . 请注意, datediff()返回一个整数,因此没有理由将任何内容声明为float

With a computed field, the value is usually calculated when you query the table. 对于计算字段,通常在查询表时计算该值。 You can materialize the value if you want using the PERSISTED keyword. 如果要使用PERSISTED关键字,可以实现该值。

Several issues I see with your trigger. 我发现触发器有几个问题。 First you can never assume only one record is going to be updated ever. 首先,您永远无法假设只有一条记录会被更新。 Enterprise databases (typically the only kind complex enough to need triggers) often are accessed outside the user application and a large insert might appear. 企业数据库(通常是唯一需要触发器的复杂数据库)通常在用户应用程序外部访问,并且可能会出现大插入。

Next, you want to get the records from an insert, so it needs to be an insert trigger. 接下来,您要从插入中获取记录,因此它需要是插入触发器。 And finally you are updating the value of the variable @period instead of the field Period in your table. 最后,您将更新变量@period的值,而不是表中的字段Period。

Try this: 尝试这个:

ALTER TRIGGER [dbo].[tr_insert_Period]
  ON  [dbo].[MEDICAL_EXCUSE]
  for insert
AS 
BEGIN

UPDATE ME
SET Period  = DATEDIFF(day,i.Start_Date , i.End_Date)
FROM MEDICAL_EXCUSE ME
JOIN Inserted i on i.id = me.id

END

You might also want this to work for updates as well, so then make it: 您可能还希望它也可以用于更新,因此使其:

FOR Insert, update

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

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