Alexander Bird
Alexander Bird

Reputation: 40639

mysql create view only if it doesn't already exist

How do I create a view only if it doesn't exist. If it does exist, I want to drop the view and redefine it. I also want no warnings or errors.

Upvotes: 9

Views: 7457

Answers (3)

Lukasz Szozda
Lukasz Szozda

Reputation: 175756

MySQL 9.1 supports IF NOT EXISTS clause:

CREATE VIEW Statement

IF NOT EXISTS causes the view to be created if it does not already exist. If the view already exists and IF NOT EXISTS is specified, the statement is succeeds with a warning rather than an error; in this case, the view definition is not changed.

CREATE VIEW IF NOT EXISTS view_name
AS 
SELECT col1, col2 FROM tab_name;

Upvotes: 1

Roland Bouman
Roland Bouman

Reputation: 31961

CREATE OR REPLACE VIEW <view name>
AS
<your select expression goes here>

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074495

You're going to kick yourself:

CREATE OR REPLACE VIEW ...

Details here. ;-)

Upvotes: 22

Related Questions