[英]SQL Server trigger to update row with linked table
I'm using SQL Server. 我正在使用SQL Server。 I have three tables,
Contacts
, Companies
and Links
. 我有三个表,
Contacts
, Companies
和Links
。
When a Contact
is inserted, I want to update columns with information from the corresponding Company
. 插入
Contact
,我想用相应Company
信息更新列。 There is a Link
table with a ToID
corresponding to the ContactID
and a FromID
corresponding to the CompanyID
. 有一个
Link
表,其中的ToID
与ContactID
相对应,而FromID
与CompanyID
相对应。
Here is the query I'm trying to use, but I'm not familiar enough with SQL to get it to work. 这是我要使用的查询,但是我对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
Thanks for any help! 谢谢你的帮助!
Kyle 凯尔
Don't understand how Links can contain a ContactId before the contact is created but this code does what you ask for. 在创建联系人之前,不了解链接如何包含ContactId,但是此代码可以满足您的要求。 (assuming ContactID is unique).
(假设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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.