I'm using SQL Server. I have three tables, Contacts, Companies and Links.
When a Contact is inserted, I want to update columns with information from the corresponding Company. There is a Link table with a ToID corresponding to the ContactID and a FromID corresponding to the CompanyID.
Here is the query I'm trying to use, but I'm not familiar enough with SQL to get it to work.
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
insertedcan contain 0, 1, or multiple rows. So anIFcheck is misguided at best - what if some of the rows match your conditions and some of them do not?