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?
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.
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.
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.
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.
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:
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With