Reputation: 181
I've recently added a new foreign key constraint (ProjectID
) to my Invoice
table and I'm trying to update the Invoice
table so that the foreign key matches with a given set of records.
Using the following query, I'm able to find the matching records.
SELECT
IV.InvoiceID, TA.ProjectID
FROM
Invoices IV
JOIN
TimeEntries TE on TE.InvoiceId = IV.InvoiceID
JOIN
Tasks TA ON TE.TaskID = TA.TaskID
I'm thinking the right way is to use a cursor and iterate through all records in the Tasks
table, but I'm not sure how to proceed.
This is what I have so far:
DECLARE @ForeignKey int
DECLARE C CURSOR FOR SELECT IV.InvoiceID, TA.ProjectID FROM Invoices IV
JOIN TimeEntries TE on TE.InvoiceId = IV.InvoiceID
JOIN Tasks TA ON TE.TaskID = TA.TaskID
OPEN C
FETCH NEXT FROM C INTO @ForeignKey
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE Invoices
SET ProjectID = @ForeignKey
WHERE InvoiceID = ??? (Need matching ID)
Thanks in advance!
Upvotes: 0
Views: 25
Reputation: 1270573
You don't need a cursor for this:
UPDATE IV
SET ProjectId = TA.ProjectID
FROM Invoices IV JOIN
TimeEntries TE
ON TE.InvoiceId = IV.InvoiceID JOIN
Tasks TA ON TE.TaskID = TA.TaskID;
Upvotes: 3