Write intelligent query with if exist ... drop.

Thursday, June 19, 2008 5:34 PM | Leave a reply »

Usually when we build a query we start the .sql file, or command in the query editor with a simple command ... CREATE PROCEDURE ... bla bla bla.

Ok but if I'm building a database from scratch is very probably that my procedure will be modified a lot of time. So every time we have to launch the command DROP PROCEDURE, or ALTER PROCEDURE.

This sounds good if you are building your object. But in case of you want to store as a BACKUP PROCEDURE some scripts in the network, is better to produce this scripts as ATOMIC and AUTOMATIC.

To accomplish this task, we can use a function really useful in SQL SERVER, IF [OBJECT] EXIST, DROP IT!

IF EXISTS (SELECT * FROM [dbo].[sysobjects] WHERE ID = object_id(N'[schema].[procedure]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [schema].[procedure] GO CREATE PROCEDURE [schema].[procedure] AS BEGIN

So now you can run the script as much time as you want.


Comments

  1. Re : # re: Write intelligent query with if exist ... drop.

    Ok, I know, this is an old post... But I was reading Your blog, and I've found this interesting.

    I use to do the same thing, but in a simpler way:

    if exists (select * from dbo.sysobjects where xtype = 'P' and name='procname')

    xtype can be 'P' for Procedures, 'FN' for functions, 'TR' for triggers, etc....

    Anyway, I'm still wondering why Microsoft still (until SQLServer 2005 - I haven't tried 2008 yet) don't have implemented the Oracle syntax :

    create [OR REPLACE] procedure|function|trigger....

    FabioG
  2. Gravatar raffaeu says:

    Re : # re: Write intelligent query with if exist ... drop.

    Ok I work with SQL 2008 and you have the same possibilities. I worked on the past with ORACLE and you can also say IF EXIST(OBJECT) without mention the kind of object.
    I don't know why probably they don't want to change the logic in the master Db ...
Comments have been closed on this topic.