你不能這樣做。
我想這可能是你想要做的?
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瞭解你的數據結構。
不完全。我需要複製費用記錄,獲取新的Id並在外部插入中使用它。這使用現有的費用記錄。 –
感謝您的編輯!不幸的是,這意味着每次用光標做一條記錄。我希望能夠在一個批次中完成,但是,如果沒有其他選擇,這是答案。 –
@ChrisWallis不,你可以批量處理。讓我進一步編輯。 – podiluska