can we write a query to check if sqlview exist or not then create view

Josh 46 Reputation points

Hi all,

can somebody help to write a query to check if view present in database , if not then create a view .

For instance :

if  not exists (SELECT * FROM sys.views WHERE OBJECT_ID = OBJECT_ID(N'[abc].[vw_name]')
    create view viewname as SELECT    ....... 

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,584 questions
{count} votes

3 answers

Sort by: Most helpful
  1. CosmogHong-MSFT 22,466 Reputation points Microsoft Vendor

    Hi @Josh

    I usually write code like this:

    IF OBJECT_ID('View_Stu_Scores')IS NOT NULL
    DROP VIEW View_Stu_Scores
    CREATE VIEW View_Stu_Scores AS
    SELECT UserName,Subject,Score
    FROM  StudentScores
    WHERE Subject = 'Math'

    Best regards,

    Cosmog Hong

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Olaf Helper 40,576 Reputation points

    Which SQL Server version are you using?

    See Update introduces CREATE OR ALTER Transact-SQL statement in SQL Server 2016 as an alternative.

    0 comments No comments

  3. Jingyang Li 5,891 Reputation points

    drop VIEW if exists [abc].[vw_name];


    CREATE or alter VIEW [abc].[vw_name]


    SELECT ...

    0 comments No comments