SQL: if exists

19Mar07

I collected these SQL scripts so that whenever I want to check the existency of a table, view, stored procedure, or function in a database, all I have to do is to copy and paste them to the Query Analyzer. FYI, These scripts are only used for SQL Server :) . Hope it's useful!

Check if the table exists in a database:

SQL:
  1. IF EXISTS
  2. (
  3.   SELECT * FROM dbo.sysobjects
  4.   WHERE id = object_id(N'[dbo].[enterTableNameHere]')
  5.          AND OBJECTPROPERTY(id, N'IsUserTable') = 1
  6. )
  7.  
  8. DROP TABLE [dbo].[enterTableNameHere]
  9.  
  10. GO

Check if the view exists in a database:

SQL:
  1. IF EXISTS
  2. (
  3.   SELECT *
  4.   FROM INFORMATION_SCHEMA.VIEWS
  5.   WHERE TABLE_NAME = 'enterViewNameHere'
  6. )
  7.  
  8. DROP VIEW [dbo].[enterViewNameHere]
  9.  
  10. GO

Check if the stored procedure exists in a database:

SQL:
  1. IF EXISTS
  2. (
  3.   SELECT * FROM dbo.sysobjects
  4.   WHERE id = object_id(N'[dbo].[enterStoredProcedureNameHere]')
  5.          AND OBJECTPROPERTY(id, N'IsProcedure') = 1
  6. )
  7.  
  8. DROP PROCEDURE [dbo].[enterStoredProcedureNameHere]
  9.  
  10. GO

Check if the user-defined function exists in a database:

SQL:
  1. IF EXISTS
  2. (
  3.     SELECT  *
  4.     FROM    INFORMATION_SCHEMA.ROUTINES
  5.     WHERE      ROUTINE_NAME   = 'enterFunctionNameHere'
  6.         AND ROUTINE_SCHEMA   = 'dbo'
  7.         AND ROUTINE_TYPE = 'FUNCTION'
  8. )
  9.  
  10. DROP FUNCTION [dbo].[enterFunctionNameHere]
  11.  
  12. GO


3 Responses to “SQL: if exists”  

  1. Gravatar 1 goz

    cara menampilkan code kayak gitu gimana mel? di WP ada plugin nya kah?

  2. Gravatar 2 yodee

    ah, a fellow programmer… at last :)

  3. Gravatar 3 oyen

    is there a good way to do a
    if exists ( selectStatementA )
    begin
    selectStatementA
    end
    ?
    It seems really clumsy to repeat the same select statement. or may be i’m not really supposed to use an “if exists” in this place o.o

    can i haz help?

Leave a Reply