我有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
答案 0 :(得分: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
答案 1 :(得分: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 DEMO 强>
答案 2 :(得分: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