Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Drop Old Stored Procedure in SQL Server

I'm writing a stored procedure in SQL Server 2008, interatively. When using SQL Server Management Studio, every very time I make an update I have to manually refresh the Programmability folder, then right-click, then delete, then OK. I could also run a query to drop the stored procedure as well.

Is there some function I can drop into stored procedure when first executing the code (from the actual stored procedure code, not the exec command) that will check to see if there is an existing stored procedure, if so, then DROP and replace with the new code?

Or, is this a bad idea due to version control?

like image 350
mikebmassey Avatar asked Mar 06 '26 01:03

mikebmassey


1 Answers

You can add this to the top of your procedure script. (just replace the ownerName and ProcName with the real values.

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[OwnerName].[ProcName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [OwnerName].[ProcName]
GO

Alternatively you can write ALTER PROC, but this may be an issue if you're saving your work as a script to be later deployed to a databases that may not have the procedure

As an aside you can always have SQL server generate this for you by right clicking on an existing procedure and selecting Script Stored Procedure as -> DROP and CREATE to -> ...

You could also use the Template Explorer Ctrl+Alt+T and use the Drop Stored Procedure template (below is the default) and then use the Query -> Specify Values for Template Parameters

-- =======================================================
-- Drop Stored Procedure 
-- =======================================================

-- Drop stored procedure if it already exists
IF EXISTS (
  SELECT * 
    FROM INFORMATION_SCHEMA.ROUTINES 
   WHERE SPECIFIC_SCHEMA = N'<Schema_Name, sysname, Schema_Name>'
     AND SPECIFIC_NAME = N'<Procedure_Name, sysname, Procedure_Name>' 
)
   DROP PROCEDURE <Schema_Name, sysname, Schema_Name>.<Procedure_Name, sysname, Procedure_Name>
GO
like image 124
Conrad Frix Avatar answered Mar 08 '26 18:03

Conrad Frix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!