Check whether a table or database exists in SQL Server

Source: Internet
Author: User

Check whether the database exists in SQL Server:
Method (1 ):

Select * from Master. DBO. sysdatabases where name = 'database name'

Method (2 ):
If db_id ('database name') is not null

Drop database...
Go

Create...

 Check whether the table object exists in SQL Server:
Select count (*) from sysobjects where id = object_id ('database name. Owner. Table name ')

If exists

(Select count (*) from sysobjects where id = object_id ('database name. Owner. Table name '))
Print 'exist'
Else
Print 'nonexistent'

In SQL Server, check whether the fields in the table exist:
If exists

(Select * From syscolumns where name = 'colname1' and ID = object_id ('database name. Owner. Table name '))
Print 'exist'
Else
Print 'nonexistent'
(Indicates that the table tablename1 contains the colname1 field)
Example:
Select * From syscolumns where name = 'test' and ID = object_id ('dbo. test ')

 

Check whether a stored procedure or view exists in SQL Server:

If object_id ('view or stored procedure name') is not null
Drop proc/view...
Go

Create proc/view...

 

Or

 

If Exists (select * from sysobjects where name = 'view or stored procedure name' AND type = 'P/V ')
Drop proc/view...
Go

Create proc/view...

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.