Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ALTER vs DROP & CREATE in SQL Server

After creating stored procedure in SQL Server why to replace Create with Alter? What will happen on execution if we do not change it? Is there a better alternate to it other then checking if exist and drop?

like image 482
user576510 Avatar asked Jun 27 '11 06:06

user576510


People also ask

What is the difference between Alter and drop?

The alter command is used when we want to modify a database or any object contained in the database. The drop command is used to delete databases from MySQL server or objects within a database.

Does alter table drop table?

ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table. ADD is used to add columns into the existing table.

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 Alter in SQL?

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The ALTER TABLE statement is also used to add and drop various constraints on an existing table.


4 Answers

Create will fail if table exists. Alter will fail if table does not exist.

If you ask why to use Alter if you can drop and create, a few reasons:

  • certain permissions already assigned to the object, you would need to regrant permissions if you drop it
  • object is probably used by other objects with schema binding
like image 160
Alex Aza Avatar answered Oct 20 '22 08:10

Alex Aza


There is no "CREATE OR REPLACE" syntax in SQL Server (like in other RDBMS)

I tend to use this pattern if I'm unsure that something exists.

IF OBJECT_ID('dbo.MyProc') IS NOT NULL
   DROP PROC dbo.MyProc
GO
CREATE PROC dbo.MyProc
...
GO
GRANT EXECUTE ---
GO
like image 2
gbn Avatar answered Oct 20 '22 08:10

gbn


From my learnings,

  • Whenever you provide a database build, It is a good practice to check if Stored Procedure exists to drop and then recreate the procedure.

  • Changing from create to alter might happen while debugging the procedure but this is not a standard practice while providing build.

like image 1
Siva Avatar answered Oct 20 '22 10:10

Siva


On the topic of helpful scripts I prefer to create the procedure if not exists and then alter it instead.

IF (select object_ID('schema.Procedure')) is null
    exec('Create procedure schema.Procedure as select 1')
GO

Alter procedure dpm.TableCellLoad

This way priviligies granted to the procedure will always remain and if the procedure did not exist it is created.

like image 1
Taher Avatar answered Oct 20 '22 08:10

Taher