使用匹配的记录SQL Server

时间:2016-02-09 12:35:20

标签: sql sql-server database

我最近在我的ProjectID表中添加了一个新的外键约束(Invoice),并且我试图更新Invoice表以便外国人密钥匹配给定的一组记录。

使用以下查询,我能够找到匹配的记录。

SELECT 
    IV.InvoiceID, TA.ProjectID 
FROM 
    Invoices IV
JOIN 
    TimeEntries TE on TE.InvoiceId = IV.InvoiceID
JOIN 
    Tasks TA ON TE.TaskID = TA.TaskID

我认为正确的方法是使用游标并遍历Tasks表中的所有记录,但我不确定如何继续。

这是我到目前为止所做的:

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)

提前致谢!

1 个答案:

答案 0 :(得分:3)

你不需要光标:

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;