The SQL statement is used to determine whether a table name exists before deletion.

Source: Internet
Author: User
Tags table name how to use sql

When using SQL, when deleting a database table, we need to determine whether the table exists before deleting it. Next let's take a look at how to use SQL to determine whether a table exists:

The SQL code is as follows:

The code is as follows: Copy code

If exists (select * from INFORMATION_SCHEMA.tables
Where table_name = 'tab ')
Drop table tab


It can be seen that the SQL statement is very simple to determine whether a table exists. Deleting the table after the judgment can avoid the error of the table.


Let's do something more advanced.

In sqlserver, check whether the table exists before creating the table. If so, delete the existing table.

 

The code is as follows: Copy code
---- SQL-Server
If exists (select 1
From sysobjects
Where id = object_id ('emp ')
And type = 'u ')
Drop table S_Evaluate
Go
 
-- CREATE Table: EMP
Create table EMP (
Id numeric identity, -- Evaluation ID
Conclusion text null -- Conclusion
Constraint PK_S_EMP primary key nonclustered (Id)

Go


Whether the temporary table exists


USE [instance name]

The code is as follows: Copy code

GO

If exists (SELECT * FROM dbo. SysObjects where id = object_id (n' [table name] ') and objectproperty (ID, 'istable') = 1)
PRINT 'exist'
ELSE
PRINT 'Nonexistent'


For example:

The code is as follows: Copy code

Use fireweb;
Go

If exists (SELECT * FROM dbo. SysObjects where id = object_id (n'temp _ TBL ') and objectproperty (ID, 'istable') = 1)
PRINT 'exist'
ELSE
PRINT 'Nonexistent'

2. Whether a temporary table exists:

Method 1:

The code is as follows: Copy code

Use fireweb;
Go

If exists (select * from tempdb .. sysobjects where id = object_id ('tempdb .. # TEMP_TBL '))
PRINT 'exist'
ELSE
PRINT 'Nonexistent'


Method 2:

The code is as follows: Copy code

Use fireweb;
Go

If exists (select * from tempdb. dbo. sysobjects where id = object_id (N 'tempdb .. # TEMP_TBL ') and type = 'u ')
PRINT 'exist'
ELSE
PRINT 'Nonexistent'

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.