Using CREATE OR ALTER

SQL Server 2017 supports the creating or altering of database objects in a single statement. This is also one of the features that has been requested for years and it is introduced in Service Pack 1 of SQL Server 2016. Use the CREATE OR ALTER statement to create an object if it does not exist, or alter it if it is already there. You can use it for stored procedures, functions, views, and triggers. Here is an example of creating or altering a scalar user-defined function:

CREATE OR ALTER FUNCTION dbo.GetWorldsBestCityToLiveIn() 
RETURNS NVARCHAR(10) 
AS 
BEGIN 
    RETURN N'Vienna'; 
END 

This is most probably the first feature you will adopt in SQL Server 2017 and it is very useful for script deployment; you don't need to check whether the object exists. Prior to SQL Server 2016 SP1, if you wanted to update a stored procedure with the latest version and you didn't know whether the previous version had been installed or not, or you simply executed the same script twice without errors, the following code was used:

IF OBJECT_ID(N'dbo.uspMyStoredProc','P') IS NULL 
  EXEC('CREATE PROCEDURE dbo.uspMyStoredProc AS SELECT NULL'); 
GO 
ALTER PROCEDURE dbo.uspMyStoredProc 
AS... 

This piece of code is error prone, awkward, and even uses dynamic SQL because CREATE PROC needs to be the first statement in a batch. Therefore, I am glad that SLQ Server finally supports a more flexible syntax for object creation and altering.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.35