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

Josh 46 Reputation points
2023-02-27T05:42:27.8566667+00:00

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]')
)
BEGIN
    create view viewname as SELECT    ....... 

END
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,697 questions
{count} votes

3 answers

Sort by: Most helpful
  1. CosmogHong-MSFT 22,861 Reputation points Microsoft Vendor
    2023-02-27T06:29:15.6566667+00:00

    Hi @Josh

    I usually write code like this:

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

    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,741 Reputation points
    2023-02-27T06:42:01.9666667+00:00

    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
    2023-03-03T03:06:27.73+00:00

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

    go

    CREATE or alter VIEW [abc].[vw_name]

    AS

    SELECT ...

    0 comments No comments