我正在使用SQL Server。我有三个表,Contacts
,Companies
和Links
。
插入Contact
后,我想更新包含相应Company
信息的列。有一个Link
表,ToID
对应ContactID
,FromID
对应CompanyID
。
这是我正在尝试使用的查询,但我对SQL不熟悉,无法使用它。
CREATE TRIGGER dbo.Contacts.AddressFromCompany
ON dbo.Contacts
AFTER INSERT AS
BEGIN
SET NOCOUNT ON
IF inserted.Address1 IS NULL AND
inserted.Address2 IS NULL AND
inserted.Address3 IS NULL AND
inserted.City IS NULL AND
inserted.State IS NULL AND
inserted.ZipCode IS NULL AND
inserted.Country IS NULL
UPDATE cont
SET Address1 = comp.Address1,
Address2 = comp.Address2,
Address3 = comp.Address3,
City = comp.City,
State = comp.State,
ZipCode = comp.ZipCode,
Country = comp.Country
FROM dbo.Companies comp
WHERE
comp.CompanyID = dbo.Links.ToID
AND dbo.Links.FromID = inserted.ContactID;
END
感谢您的帮助!
凯尔
答案 0 :(得分:1)
在创建联系人之前,不要理解Links如何包含ContactId,但此代码可以满足您的要求。 (假设ContactID是唯一的)。
UPDATE Contacts
SET Address1 = Companies.Address1
,Address2 = Companies.Address2
,Address3 = Companies.Address3
,City = Companies.City
,State = Companies.State
,ZipCode = Companies.ZipCode
,Country = Companies.Country
FROM Contacts
INNER JOIN Links
ON Links.FromID = Contacts.ContactsID
INNER JOIN Companies
ON Companies.CompanyID = Links.ToID
INNER JOIN inserted
ON inserted.ContactId = Contacts.ContactID
WHERE inserted.Address1 IS NULL
AND inserted.Address2 IS NULL
AND inserted.Address3 IS NULL
AND inserted.City IS NULL
AND inserted.State IS NULL
AND inserted.ZipCode IS NULL
AND inserted.Country IS NULL