我整个下午都被困在这里,最后放弃了。我需要每个月定期为多个客户创建月度发票。
所以我从[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 :(得分: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