所以这是一个类似于另一个的学校问题我得到了一个代码:
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)
我必须设置sys.views.name = ...的位置,并设置一个exec命令,以便创建视图运行'first'。
答案 0 :(得分:1)
在回复您的评论时,请务必使用GO
语句围绕您的视图定义:
if exists (select * from sys.views where name = 'ThreeDigitsOfPi')
drop view dbo.ThreeDigitsOfPi
GO
create view dbo.ThreeDigitsOfPi
as
select 3.14 as PI
GO
其他一些观点:
'
代替‘
样式引号create view NameOfView as ...
)view
定义不能遵循if
语句,除非视图是在动态SQL中创建的。例如:if not exists (...) exec('create view ...')
答案 1 :(得分:1)
有多种方法可以检查视图是否存在。但是,通常的方法是删除视图(如果存在),然后重新创建它:
IF EXISTS (SELECT * FROM sys.views Where name = ‘EarliestInvoiceandTotalVEW’)
drop view EarliestInvoiceandTotalVEW;
然后,您的create view
声明有两个缺陷。首先,它缺少一个名字。其次,它内嵌了create view
。您必须决定要创建哪一个 - 子查询的视图或整个语句的视图(我不清楚问题是正确的方法)。