2013-10-17 211 views
0

我想要做一個INSERT INTO SELECT語句,並在SELECT中嵌入一個進一步的INSERT。原因是我需要複製一個外鍵,並在外部插入中使用新的行ID。事情是這樣的:INSERT嵌入INSERT INTO SELECT

INSERT INTO Contracts ( 
    JobId, 
    InvoiceNumber 
    ExpensesId) 
SELECT 
    j.Id, 
    j.InvoiceNumber, 
    (INSERT INTO Expenses (Bus, Toll) SELECT Bus, Toll FROM Expenses WHERE Id = j.ExpensesId) 
FROM Jobs j 

此SQL不運行,因爲INSERT不返回任何東西,但有沒有辦法做到這一點,或一個更好的方法?

回答

4

你不能這樣做。

我想這可能是你想要做的?

INSERT INTO Contracts ( 
    JobId, 
    InvoiceNumber 
    ExpensesId) 
SELECT 
    j.Id, 
    j.InvoiceNumber, 
    j.ExpensesID 
FROM Expenses 
    INNER JOIN Jobs j ON expenses.Id = j.ExpensesId 

如果你需要複製的費用行,你需要做的,首先,用SCOPE_IDENTITY以獲取新的ID。

declare @expenseid int = -- your expense ID 
declare @newid int 

INSERT Expenses (Bus, Toll) 
SELECT Bus, Toll FROM Expenses WHERE Id = @expenseID 
SELECT @newID = SCOPE_IDENTITY() 

INSERT INTO Contracts ( 
    JobId, 
    InvoiceNumber 
    ExpensesId) 
SELECT 
    j.Id, 
    j.InvoiceNumber, 
    @newID 
FROM Expenses 
WHERE Id = @expenseID 

如果你想要做一個批處理

DECLARE @inserts table(expenseid int, jobid int) 

INSERT Expenses (Bus, Toll) 
OUTPUT inserted.id, Jobs.ID INTO @inserts 
SELECT Bus, Toll FROM Expenses 
     INNER JOIN Jobs ON Jobs.ExpenseID = Expenses.ID 

INSERT Contracts (JobID, InvoiceNumber, ExpensesID) 
SELECT j.ID, j.InvoiceNumber, i.ExpenseID 
FROM Jobs j 
    INNER JOIN @inserts I on j.ID = i.jobid 

...或者類似的東西 - 不能肯定我compeletely瞭解你的數據結構。

+0

不完全。我需要複製費用記錄,獲取新的Id並在外部插入中使用它。這使用現有的費用記錄。 –

+0

感謝您的編輯!不幸的是,這意味着每次用光標做一條記錄。我希望能夠在一個批次中完成,但是,如果沒有其他選擇,這是答案。 –

+0

@ChrisWallis不,你可以批量處理。讓我進一步編輯。 – podiluska

0

你不能在select語句中寫入插入。它不返回列字段或對象