2012-04-03 77 views
2

我一直在这一整天下午陷入困境,最后放弃。我需要每个月定期为多个客户创建月度发票。SQL将多行插入到第二个/子表中

因此,我从[Customers - Main]表中获取数据并创建了所需的所有[INVOICES]行。但是,我无法使[客户 - 发票]正确填充每张发票。应该发生的是[发票 - 库存链接]中填入[客户 - 发票]中的正确信息。目前,每个客户项目均填入1张发票。

这是我到目前为止的代码,任何帮助将感激地收到。

ALTER PROCEDURE [aa test] 

AS 

INSERT INTO dbo.[INVOICES] 
(
    CompanyName, InvoiceDate, PurchaseOrderNo, Terms 
    , JobNumber, PrintableNotes, Initials 
) 
SELECT dbo.[CUSTOMERS - Main].CompanyName 
    , DATEADD(d, - 15, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0)) AS Expr1 
    , 'test3' AS pono, 7 AS terms, 0 AS jobno 
    , 'We will attempt to collect this invoice by Direct Debit' AS printnotes 
    , 'KA' AS initials 
FROM dbo.[CUSTOMERS - Main] 
INNER JOIN dbo.[CUSTOMERS - Invoices] 
ON dbo.[CUSTOMERS - Main].CustID = dbo.[CUSTOMERS - Invoices].CustID 
WHERE (dbo.[CUSTOMERS - Invoices].Annual <> 1) And 
    (dbo.[CUSTOMERS - Invoices].DayofMonth = 15) 
GROUP BY dbo.[CUSTOMERS - Main].CompanyName 

SELECT @endInvoice=MAX(InvoiceNo) FROM INVOICES 

INSERT INTO dbo.[INVOICES - Stock Link] (InvoiceNo, StockID, SalePrice) 
SELECT @endinvoice, StockID, Price 
FROM dbo.[CUSTOMERS - Invoices] 
+0

,我们在谈论什么数据库? – 2012-04-03 14:08:58

+4

评论,因为这是不相关的 - 请考虑使用数据库模式,而不是在表名中放置空格。 – 2012-04-03 14:22:35

+0

Nikola它是一个SQL Server 2005. Norla,我知道,它是从1997年开始的遗留数据库!这就是为什么名称中有空格。改变与之相关的所有视图和VBA代码是一项艰巨的任务。 – alcomcomputing 2012-04-03 14:51:42

回答

5

您可以使用OUTPUT条款由Nikola Markovinović提到:

ALTER PROCEDURE [aa test] 

AS 

-- Setup storage for the inserted keys 
DECLARE @INVOICES TABLE (InvoiceNo int not null primary key) 

INSERT INTO dbo.[INVOICES] 
(
    CompanyName, InvoiceDate, PurchaseOrderNo, Terms 
    , JobNumber, PrintableNotes, Initials 
) 
-- Grab the inserted keys 
OUTPUT INSERTED.InvoiceNo INTO @INVOICES 
SELECT dbo.[CUSTOMERS - Main].CompanyName 
    , DATEADD(d, - 15, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0)) AS Expr1 
    , 'test3' AS pono, 7 AS terms, 0 AS jobno 
    , 'We will attempt to collect this invoice by Direct Debit' AS printnotes 
    , 'KA' AS initials 
FROM dbo.[CUSTOMERS - Main] 
INNER JOIN dbo.[CUSTOMERS - Invoices] 
ON dbo.[CUSTOMERS - Main].CustID = dbo.[CUSTOMERS - Invoices].CustID 
WHERE (dbo.[CUSTOMERS - Invoices].Annual <> 1) And 
    (dbo.[CUSTOMERS - Invoices].DayofMonth = 15) 
GROUP BY dbo.[CUSTOMERS - Main].CompanyName 

INSERT INTO dbo.[INVOICES - Stock Link] (InvoiceNo, StockID, SalePrice) 
-- Not sure where StockID and Price come from 
SELECT a.InvoiceNo, a.StockID, a.Price 
FROM dbo.[CUSTOMERS - Invoices] a 
    -- Join on the keys from above 
    JOIN @INVOICES b ON a.InvoiceNo = b.InvoiceNo