所以这是一个类似于另一个我得到代码的学校问题:
USE AP
SELECT VendorName, FirstInvoiceDate, InvoiceTotal
FROM Invoices JOIN
(SELECT VendorID, MIN(InvoiceDate) AS FirstInvoiceDate
FROM Invoices
GROUP BY VendorID) AS FirstInvoice
ON (Invoices.VendorID = FirstInvoice.VendorID AND
Invoices.InvoiceDate = FirstInvoice.FirstInvoiceDate)
JOIN Vendors
ON Invoices.VendorID = Vendors.VendorID
ORDER BY VendorName, FirstInvoiceDate
我需要更改它以创建视图而不是派生表我想的更像
IF NOT EXISTS (SELECT * FROM sys.views
Where name = ‘EarliestInvoiceandTotalVEW’)
CREATE View AS
Select VendorName, FirstInvoiceDate, InvoiceTotal
From Invoices JOIN
(Create VIEW FirstInvoice AS
SELECT VendorID, MIN(InvoiceDate) AS FirstInvoiceDate
From Invoices
Group By VendorID) As FirstInvoice
ON (Invoices.VendorID = FirstInvoice.VendorID AND
Invoices.InvoiceDate = FirstInvoice.FirstInvoiceDate)
JOIN Vendors
ON Invoices.VendorID = Vendors.VendorID
ORDER BY VendorName, FirstInvoiceDate
这将使视图执行相同的操作并检查它是否存在,因此不会每次都重新创建/定义它。
感谢您对此的任何意见!
对于我直接从 SQL Server 中取出的格式,我深表歉意,它通常格式正确......
这就是我要工作的:
USE AP
Declare @Create1 varchar(8000)
IF EXISTS (SELECT * FROM sys.views Where sys.views.name = 'EarliestInvoiceandTotalVIEW')
drop view EarliestInvoiceandTotalVIEW;
SET @CREATE1 = 'CREATE View EarliestInvoiceTotalVIEW AS
Select VendorName, FirstInvoiceDate, InvoiceTotal
From Invoices JOIN
(SELECT VendorID, MIN(InvoiceDate) AS FirstInvoiceDate
FROM Invoices
GROUP BY VendorID) AS FirstInvoice
ON (Invoices.VendorID = FirstInvoice.VendorID AND
Invoices.InvoiceDate = FirstInvoice.FirstInvoiceDate)
JOIN Vendors
ON Invoices.VendorID = Vendors.VendorID'
Exec (@CREATE1)
我必须将 where 设置为 sys.views.name =... 并设置一个 exec 命令,以便创建视图“首先”运行。