Dropping and recreating a stored procedure if it already exists.

I have a sql script and it needs to determine if a stored procedure already exists. If it does exists, I need to replace the stored procedure. I am using Sql server 2012. My approach is to check if the stored procedure exists. If it does exists then I want to drop it and recreate it. So below is my code. I have two questions. 1. Is the code acceptable? 2. do I need to preference the stored procedure with [dbo'] ?

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.ROUTINES
  WHERE ROUTINE_NAME = 'MySP'
        AND ROUTINE_TYPE = 'PROCEDURE')
BEGIN
DROP PROCEDURE [dbo].[MySP]
END
LVL 2
brgdotnetcontractorAsked:
Who is Participating?
 
Mark WillsTopic AdvisorCommented:
I always prefer to drop then recreate.

IF object_id('dbo.mySP','P') is not null drop procedure dbo.mySP
go
create procedure dbo.mySP (etc)

Open in new window

And always use schema name - even if defaulting to dbo

Main reason to drop + create is recompiles and picking up latest stats... especially if changing the nature of the procedure.
3
 
slightwv (䄆 Netminder) Commented:
In 2016 you have create or alter.

There may be a better trick but in 2012 it looks like you need to query the data dictionary first:
http://www.sqlservercentral.com/blogs/martin_catherall/2011/05/04/how-do-you-create-or-update-stored-procedures_2E00_/
0
 
brgdotnetcontractorAuthor Commented:
Ok, thank. What if I am using 2012. Again, is my approach acceptable?

Do I need the [dbo]
0
 
slightwv (䄆 Netminder) Commented:
I mentioned the pre 2016 method which is similar to what you posted.

It appears to be the correct way to do things.  As far as needing DBO, test it.  It will either work or not?

My SQL Server isn't that strong and I'm not sure if other schemas can own procedures.  I cannot speak to specifics.
0
 
Mark WillsTopic AdvisorCommented:
By way of example :
If object_id('dbo.my_test_sp','P') is not null drop procedure dbo.my_test_sp
go

create procedure dbo.my_test_sp 
as
begin 
     select 'Hello World'
end
go

exec dbo.my_test_sp

Open in new window

1
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.