how to have dynamically create & alter in the sql script?
Instead of having if exits - drop we are looking to have if exits - alter.
How to handle such scenario.
how to have dynamically create & alter in the sql script?
Instead of having if exits - drop we are looking to have if exits - alter.
How to handle such scenario.
To clarify my comments above, SQL Server 2016 SP1 released a CREATE OR ALTER
statement that will either create an object that doesn't already exists or modify the object if it does. This is only allowed on certain objects such as stored procedures, triggers, functions, and views. Tables, indexes, and other objects that are allocated storage cannot be used in by the CREATE OR ALTER
statement. Also note that since they're persisted on disk, indexes views are not permitted to be used by this. A basic example of the syntax is below.
CREATE OR ALTER PROCEDURE SP_TestStoredProcedure
AS
BEGIN
SELECT
Column1,
Column2,
Column3
FROM YourTable
END
Here is a trick I've used.
-- for testing, not needed for real -- DROP PROCEDURE dbo.uspDoSomething
GO
IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE = 'PROCEDURE' and ROUTINE_NAME = 'uspDoSomething' )
BEGIN
EXEC ( 'CREATE PROCEDURE dbo.uspDoSomething(@i INT) AS BEGIN RAISERROR (''Stubbed version'' , 16, -1) END' )
END
GO
--test only
EXEC dbo.uspDoSomething 0
GO
ALTER PROCEDURE dbo.uspDoSomething(@PatientKey INT)
AS
BEGIN
SELECT @@VERSION
END
GO
--test only
EXEC dbo.uspDoSomething 0
GO
Remember, an ALTER does not change all the PERMISSIONS you have on the script. A DROP/ADD needs permissions reapplied.
Note, you did not originally mention your sql-server version. This trick works with 2014 and before. Obviously, newer versions with CREATE OR ALTER would be preferred over EXEC with dynamic sql.