我正在尝试执行INSERT INTO SELECT语句,并在SELECT中嵌入了另一个INSERT。原因是我需要复制一个外键并在外部插入中使用新的行id。像这样:
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没有返回任何内容,但有没有办法做到这一点,或者更好的方法?
答案 0 :(得分:3)
你不能那样做。
我认为这可能是你想要做的事情?
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
......或类似的东西 - 不太确定我是否能够完全理解您的数据结构。
答案 1 :(得分:0)
您无法在select语句中编写insert。它不返回列字段或对象