Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DROP...CREATE vs ALTER

When it comes to creating stored procedures, views, functions, etc., is it better to do a DROP...CREATE or an ALTER on the object?

I've seen numerous "standards" documents stating to do a DROP...CREATE, but I've seen numerous comments and arguments advocating for the ALTER method.

The ALTER method preserves security, while I've heard that the DROP...CREATE method forces a recompile on the entire SP the first time it's executed instead of just a a statement level recompile.

Can someone please tell me if there are other advantages / disadvantages to using one over the other?

like image 271
DCNYAM Avatar asked Oct 29 '09 16:10

DCNYAM


People also ask

What is the difference between alter and create in SQL?

The advantage of using ALTER PROCEDURE to change a stored procedure is that it preserves access permissions, whereas CREATE PROCEDURE doesn't. A key difference between them is that ALTER PROCEDURE requires the use of the same encryption and recompile options as the original CREATE PROCEDURE statement.

What is drop and create?

First DROP and CREATE. This method involves first checking to see if an object already exists and if it does exist dropping it. Next you can create the object freely.

Does ALTER PROCEDURE force recompile?

ALTER will also force a recompile of the entire procedure. Statement level recompile applies to statements inside procedures, eg.

What does ALTER PROCEDURE do in SQL?

The ALTER PROCEDURE statement allows changes to be made to an existing stored procedure.


2 Answers

ALTER will also force a recompile of the entire procedure. Statement level recompile applies to statements inside procedures, eg. a single SELECT, that are recompiled because the underlying tables changes, w/o any change to the procedure. It wouldn't even be possible to selectively recompile just certain statements on ALTER procedure, in order to understand what changed in the SQL text after an ALTER procedure the server would have to ... compile it.

For all objects ALTER is always better because it preserves all security, all extended properties, all dependencies and all constraints.

like image 106
Remus Rusanu Avatar answered Sep 25 '22 00:09

Remus Rusanu


This is how we do it:

if object_id('YourSP') is null     exec ('create procedure dbo.YourSP as select 1') go alter procedure dbo.YourSP as ... 

The code creates a "stub" stored procedure if it doesn't exist yet, otherwise it does an alter. In this way any existing permissions on the procedure are preserved, even if you execute the script repeatedly.

like image 32
Andomar Avatar answered Sep 23 '22 00:09

Andomar