SQL Server determine if table exists method

Source: Internet
Author: User

Before you create a table, you usually need to determine if the table already exists, and if it does, you do not need to create it, and sometimes you need to determine whether it exists before you delete the table, or you will get an error.

There are roughly two ways of judging the method:

Method One:

if Exists(Select Top 1 1  fromSysObjectswhereId=object_id(N'Le_user') andXtype='U')       Print 'exist'Else     Print 'does not exist'

Method Two:

if object_id (n'le_user', n'U'is notnull    print' exists ' else     Print ' does not exist '

Both of these methods use the sysobjects system table, which holds all object information, since it is all objects, naturally including the information of the table, where xtype is represented by U as the user table.

The method for determining whether a temporary table exists is as follows:

if object_id(N'tempdb: #TempTable'N'U') is  not NULL    Print 'exist'Else     Print 'does not exist'if exists(Select *  fromTempdb.dbo.sysobjectswhereId= object_id(N'tempdb: #TempTable') andType='U')   Print 'exist' Else   Print 'does not exist'

The temporary table itself is also a table, so judging the existence of the method is the same as the normal table, but need to increase tempdb. Indicates a temporary table.

SQL Server determine if table exists method

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.