在此网站http://www.w3schools.com/sql/sql_view.asp上,它表示我可以按如下方式更新视图:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No
但是,我创建了如下所示的视图:
CREATE VIEW ProductCustomers AS
SELECT cust_name, cust_contact, prod_id
FROM Customers, Orders, OrderItems
WHERE Customers.cust_id = Orders.cust_id
AND Orders.order_num = OrderItems.order_num
然后尝试通过建议的语法更新它:
CREATE VIEW ProductCustomers AS
SELECT cust_name, cust_contact, prod_id,cust_address --JUST ADDING THE COLUMN cust_address
FROM Customers, Orders, OrderItems
WHERE Customers.cust_id = Orders.cust_id
AND Orders.order_num = OrderItems.order_num
我得到错误:“数据库中已经有一个名为'ProductCustomers'的对象。数据库中已经有一个名为'ProductCustomers'的对象。”所以我不确定如何在我的视图中添加新列。
由于
答案 0 :(得分:4)
您需要使用ALTER VIEW
ALTER VIEW ProductCustomers AS
答案 1 :(得分:0)
DROP VIEW ProductCustomers
GO
CREATE VIEW ProductCustomers AS
SELECT cust_name, cust_contact, prod_id,cust_address FROM Customers, Orders, OrderItems
WHERE Customers.cust_id = Orders.cust_id
AND Orders.order_num = OrderItems.order_num
Go
答案 2 :(得分:0)
这是我在定义对象时使用的一种实用方法(在本例中是一个视图)。
if object_id('[dbo].[viewName]') is not null --object already exists
set noexec on;
go
create view [dbo].[viewName] as
select 'not implemented' as message
go
set noexec off;
go
alter view [dbo][viewName] as
--your actual view definition here
作为解释,此代码检查视图是否已存在。如果它不存在,则创建存根。一旦执行或跳过存根创建部分,就会保证存在该名称的视图,因此保证alter view
语句可以正常工作。