The or replace clause allows you to replace a view's definition using create view.
Changes are in bold.
create [or replace] view [owner.]view_name [(column_name[, column_name]...)] as select [distinct] select_statement [with check option]
Example 1
This example is based on the view Current_Product_List which lists all active products from the table Products. The view is defined as:
create view Current_Product_List as select ProductID, ProductName from Products where Discontinued = “No” select object_id("Current_Product_List") ----------- 889051172
This next command adds the Category column to Current_Product_list using the or replace clause. The object ID of the view remains the same:
create or replace view Current_Product_List as select ProductID, ProductName, Category from Products where Discontinued = “No” select object_id("Current_Product_List") ----------- 889051172
Example 2
In this example, V1—a view that has dependent objects—is replaced:
create table T1(C1 int, C2 int) create table T2(C1 int, C2 int) create view V1 as select * from T1 create view V2 as select * from V1 create function foo1 returns int as begin declare @number int select @number = C1 from V2 end return @number select object_id("V1") ----------- 985051514
create or replace V1 as select * from T2 select * from V2 select dbo.foo1() select object_id("V1") ----------- 985051514
The replaced version of V1 references T2 instead of T1. Both V2 and foo1 will be recompiled. select * from v2 recompiles V2, but not foo1, which is recompiled when the UDF is invoked.
create view V1 as select C1 from T1 create procedure P as select * from V1
create or replace V1 as select C1, C2 from T1
create view V2 as select C1, C2 from T2 create procedure P as select C2 from V2
create or replace V2 as select C1 from T2
Before you replace a view, run sp_depends to determine if there are any stored procedures or parent views that depend on the view you are replacing. If such stored procedures or parent views exist, replace the stored procedures or parent views as necessary after replacing the view.
If a view has permissions granted at the column level, then it cannot be replaced and error 2014 is raised. To replace the view, you must first revoke the permissions, or drop and re-create the view.
Any user who impersonates the view owner through an alias or setuser cannot replace the view.
Changes for replacing a view are in bold.
Granular permissions enabled | With granular permissions enabled, you must have the create view privilege. You must have the create any view privilege to run create view for other users. You must be the view owner to replace the view. |
Granular permissions disabled | With granular permissions disabled, you must be the database owner or have the create view privilege. You must be the view owner to replace the view. |
Changes are in bold.
Event | Audit Option | Command or access audited | Information in extrainfo |
---|---|---|---|
13 | create | create view |
|