create if not exists view?
46,107
Solution 1
From section 12.1.12. CREATE VIEW Syntax of the MySQL 5.0 Reference Manual:
CREATE VIEW Syntax
CREATE
[OR REPLACE]
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
The CREATE VIEW statement creates a new view, or replaces an existing one if the OR REPLACE clause is given. This statement was added in MySQL 5.0.1. If the view does not exist, CREATE OR REPLACE VIEW is the same as CREATE VIEW. If the view does exist, CREATE OR REPLACE VIEW is the same as ALTER VIEW.
Solution 2
The usual way is to overwrite a view using create or replace
:
create or replace view YourView
as
select * from users
Solution 3
On H2 you can add IF NOT EXISTS before the view name you want to create. e.g.:
CREATE VIEW IF NOT EXISTS viewExampleName (column1, column2)
AS (
SELECT column1, column2
FROM example_table
);
Author by
kumar kasimala
Updated on September 27, 2020Comments
-
kumar kasimala over 3 years
Is there any way to
create view if not exists
in MySQL or H2 Database? -
Nicolas over 13 yearsThis answers the question partially; How do you do that in H2?
-
flymike almost 9 yearsBut, if an existing view is replaced, don't its dependent views become invalid? That's why there's a need to test for the existence of a view.
-
obe over 5 yearsThe result of using CREATE OR REPLACE is NOT the same as CREATE IF NOT EXISTS. The former would overwrite an existing view, whereas the latter would not (if it were available in MySQL...)
-
sports over 4 yearsin SQL Server is
create or alter view YourView as ...
-
petrch about 3 yearsIs this this H2 database? h2database.com/html/commands.html#create_view I cannot see
IF NOT EXISTS
anywhere. -
Daniel about 3 yearsYes, it is for H2. On the link you just posted you can see the "IF NOT EXISTS" on the image under the title "CREATE VIEW"
-
petrch about 3 yearsOh, thanks, my fault, I clearly did a poor search. I am sorry.
-
ChrCury78 almost 3 yearsThe server I am using (probably old one) is MySQL version 5.5 does not recognize "IF NOT EXISTS" but "CREATE OR REPLACE VIEW .. " worked fine.
-
Daniel almost 3 yearsUnderstand. This command i wrote is for H2 database.