SQL server first checks whether a view exists and then creates a view statement. SQL SERVER

Source: Internet
Author: User

SQL server first checks whether a view exists and then creates a view statement. SQL SERVER

If our statement is:

IF NOT EXISTS(SELECT 1 FROM sys.views WHERE name='Report_IndividualTicket')BEGINcreate view Report_IndividualTicketasSELECT Ticket.TicketNumber, Ticket.TicketID,GisProcess.StageName,Content.DtReceived, Content.ContentTextFROM(GisProcess INNER JOIN TicketON GisProcess.TicketID=Ticket.TicketID)INNER JOIN ContentON Ticket.ContentID=Content.ContentIDEND

The following error is prompted:

Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'view '.

The cause of this error is that the "create view" statement must be the first one in batch processing.

Therefore, you can modify the statement:

IF EXISTS(SELECT 1 FROM sys.views WHERE name='Report_IndividualTicket')DROP VIEW Report_IndividualTicketGOcreate view Report_IndividualTicketasSELECT Ticket.TicketNumber, Ticket.TicketID,GisProcess.StageName,Content.DtReceived, Content.ContentTextFROM(GisProcess INNER JOIN TicketON GisProcess.TicketID=Ticket.TicketID)INNER JOIN ContentON Ticket.ContentID=Content.ContentIDGO

How does SQL server determine whether a view exists?

SELECT count (*) as cut FROM sysviews WHERE object_id = '[dbo]. [view name]'
If fieldByName ('cut ')> 0 then
// Exists
Else
// Does not exist

SQL server determines whether a view exists

First, judge whether the following statements return results, and then judge.

SELECT * from dbo. sysobjects B where B. XTYPE = 'V' and B. NAME = 'A'

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.