So This is a school question similar to another I was given a code:
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
I need to change this to create a view instead of a derived table I was thinking something more like
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
This would make a view to do the same thing and check if it exists so it is not recreated/defined each time.
Thanks for any input on this!
I apologize about the format I took it directly out of SQL Server and it normally is formatted well...
This is what I got to work:
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)
I had to set the where to sys.views.name =... as well as set an exec command so that the create view is running 'first'.
create, it should becreate view [EarliestInvoiceandTotalVEW] as --etc.