0

我正在尝试执行 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 不返回任何内容,但有没有办法做到这一点,或者更好的方法?

4

2 回答 2

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

...或类似的东西-不太确定我完全理解您的数据结构。

于 2013-10-17T08:30:18.927 回答
0

您不能在 select 语句中编写插入。它不返回列字段或对象

于 2013-10-17T08:36:03.973 回答