![](/img/trans.png)
[英]SQL Server - loop through temp table and calculate multiple values to insert rows into second table
[英]SQL insert multiple rows into a second/sub table
我一直呆在整個下午,最后放棄了。 我需要每月定期為多個客戶創建月度發票。
因此,我從[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]
您可以使用NikolaMarkovinović提到的OUTPUT
子句:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.