chiru
chiru

Reputation: 832

How to check whether table exists in SQL

if (1st table exists) then select date from 1st table and call a (procedure) how to do this?

Upvotes: 2

Views: 7172

Answers (2)

gvee
gvee

Reputation: 17171

I like this method for checking an objects existence.

IF Object_ID('dbo.your_table', 'U') IS NOT NULL
  BEGIN
    /* Table exists */
  END
ELSE
  BEGIN
    /* Table does not exist */
  END

The Object_ID() function returns the... object_id(!) of the specified object. If the object doesn't exist then it returns NULL. The second [optional] parameter being passed here is a U which is the object type (U=User table, V=View, P=Procedure... see type column here for more info here).

Basically this is a short hand (lazy? ahem) method of checking for an objects existence

Upvotes: 7

Nadeem_MK
Nadeem_MK

Reputation: 7689

Verify if the table exists before proceeding;

IF  NOT EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[YourTable]') AND type in (N'U'))

Upvotes: 1

Related Questions