Link to home
Start Free TrialLog in
Avatar of brgdotnet
brgdotnetFlag for United States of America

asked on

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
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

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_/
Avatar of brgdotnet

ASKER

Ok, thank. What if I am using 2012. Again, is my approach acceptable?

Do I need the [dbo]
SOLUTION
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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