0

我有 2 个表 A 和 B

表A数据


Enquiry_Id  Ckeck_In    check_Out   Place
129         2013-09-20  2013-09-23  Delhi
130         2013-08-09  2013-08-10  Agra
130         2013-08-10  2013-08-12  Punjab
130         2013-08-12  2013-08-13  Haryana

表 B 数据

 Enquiry_Id        Arrives_On   Arrives_Details      
  129              2013-09-20       NA            
  130              2013-08-09       NA           

我想当我将我的表 B Arrives_on Date 2013-08-09 更新为 2012-08-14 其中 enquiry_Id 为 130 时,我的表 A 数据将自动更改 check_In 和 Check_Out 日期。喜欢

 Enquiry_Id Ckeck_In    check_Out   Place
129         2013-09-20  2013-09-23  Delhi
130         2013-08-14  2013-08-15  Agra
130         2013-08-15  2013-08-17  Punjab
130         2013-08-17  2013-08-18  Haryana
4

3 回答 3

0

您可以在表 B 的数据库中创建更新触发器

CREATE TRIGGER trgAfterUpdate ON [dbo].[B] 
FOR UPDATE
AS
    declare @ArrivesOn datetime;
    declare @id int;

    SELECT @id =i.Enquiry_Id, @ArrivesOn=Arrives_On from inserted i;   

      -- perform update.insert here  like
      -- Insert into A(Enquiry_Id,NewDate) values(@id ,@ArrivesOn)

GO
于 2013-09-11T07:28:28.000 回答
0

在 TableB 上触发,您可以在其中计算先前 ( DELETED) 和更新 ( INSERTED) 值之间的差异,并将该差异添加到您的TableA列中。

CREATE TRIGGER tgTableBUpdate ON TableB
AFTER UPDATE 
AS
BEGIN

    UPDATE a
        SET a.Ckeck_In = DATEADD(DD, DATEDIFF(DD,d.Arrives_On, i.Arrives_On), a.Ckeck_In)
       ,a.Check_Out = DATEADD(DD, DATEDIFF(DD,d.Arrives_On, i.Arrives_On), a.check_Out)
    FROM INSERTED i
    INNER JOIN DELETED d ON i.Enquiry_Id = d.Enquiry_Id
    INNER JOIN dbo.TableA a ON i.Enquiry_Id = a.Enquiry_Id AND d.Enquiry_Id = a.Enquiry_Id

END

SQLFiddle 演示

于 2013-09-11T07:31:41.407 回答
0

您必须为此使用触发器。

USE [YOUR_DATABASE]
GO
CREATE TRIGGER [dbo].[UpdateCheckInCheckOutDates] ON [dbo].[Table_B]
AFTER UPDATE
AS
BEGIN
  DECLARE @Before_Date date, @After_Date date, @Date_Diff smallint, @Id int
  SET @Date_Diff = 0

  SELECT @Id = D.Enquiry_Id, @Before_Date = D.Arrives_On FROM DELETED D
  SELECT @After_Date = I.Arrives_On FROM INSERTED I

  IF UPDATE(Arrives_On)
  BEGIN 
    SET @Date_Diff = DATEDIFF(day, @Before_Date, @After_Date)
    IF(@Date_Diff) <> 0)
    BEGIN
      UPDATE Table_A SET Check_In = @After_Date,
             Check_Out = DATEADD(DD, @Date_Diff, @After_Date)
             WHERE Enquiry_Id = @Id
    END
  END
END
于 2013-09-11T07:44:36.083 回答