DROP IF EXISTS Statement in Sql Server 2016

In Sql Server 2016, IF EXISTS is the new optional clause introduced in the existing DROP statement. Basically, it checks the existence of the object, if the object does exists it drops it and if it doesn’t exists it will continue executing the next statement in the batch. Basically it avoids writing if condition and within if condition writing a statement to check the existence of the object.

Syntax:

DROP OBJECT_TYPE [ IF EXISTS ] OBJECT_NAME

WHERE: OBJECT_TYPE like Table, Procedure, View, Function, Database, Trigger, Assembly, Sequence, Index etc.

IF EXISTS: It is an optional clause and if it is mentioned in the DROP statement then it checks the existence of the object, if it exists it will drop otherwise continues executing the next statement in the block without raising any issues.

Let us understand this new IF EXISTS clause in the DROP statement with an extensive list of examples. To demonstrate this clause let us first create a sample Database with a Table and a Stored Procedure.

CREATE DATABASE SqlHintsDemoDB
GO
USE SqlHintsDemoDB
GO
CREATE TABLE dbo.Customers  (Id INT, Name Nvarchar(50))
GO
CREATE PROCEDURE dbo.WelcomeMessage
AS
	SELECT 'Welcome to Sql Server'
GO

DROP Stored Procedure IF EXISTS

[ALSO READ] How to check if a Stored Procedure exists

In Sql Server 2016 we can write a statement like below to drop a Stored Procedure if exists.

DROP PROCEDURE IF EXISTS dbo.WelcomeMessage

DROP PROCEDURE IF EXISTS

If the stored procedure doesn’t exists it will not raise any error, it will continue executing the next statement in the batch. Let’s try to re-drop the stored procedure WelcomeMessage which is already dropped.

DROP PROCEDURE IF EXISTS Sql Server 2016

From the result it is clear that it will not raise any error if the stored procedure doesn’t exists, it will continue executing the next statement in the batch.

In previous versions of Sql Server we use statement like below to drop the stored procedure if exists.

IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE Name = 'WelcomeMessage')
BEGIN
    DROP PROCEDURE dbo.WelcomeMessage
END

You can go through the article How to check if a Stored Procedure exists to see various options in the previous versions of Sql Server to check for the existence of a Stored Procedure.

DROP TABLE IF EXISTS

[ALSO READ] How to check if a Table exists

In Sql Server 2016 we can write a statement like below to drop a Table if exists.

DROP TABLE IF EXISTS dbo.Customers

DROP TABLE IF EXISTS

If the table doesn’t exists it will not raise any error, it will continue executing the next statement in the batch. Let’s try to re-drop the Table dbo.Customers which is already dropped.

DROP TABLE IF EXISTS Sql Server 2016

From the result it is clear that it will not raise any error if the Table doesn’t exists, it will continue executing the next statement in the batch.

In previous versions of Sql Server we use statement like below to drop the Table if exists.

IF EXISTS(SELECT 1 FROM sys.Tables 
          WHERE  Name = N'Customers' AND Type = N'U')
BEGIN
  DROP TABLE dbo.Customers
END

You can go through the article How to check if a Table exists to see various options in the previous versions of Sql Server to check for the existence of a Table.

DROP DataBase IF EXISTS

[ALSO READ] How to check if a Database exists

In Sql Server 2016 we can write a statement like below to drop a DataBase if exists.

USE MASTER
GO
DROP DATABASE IF EXISTS SqlHintsDemoDB

DROP DATABASE IF EXISTS

If the Database doesn’t exists it will not raise any error, it will continue executing the next statement in the batch. Let’s try to re-drop the Database SqlHintsDemoDB which is already dropped.

DROP DATABASE IF EXISTS Sql 2016

From the result it is clear that, it will not raise any error if the Database doesn’t exists, it will continue executing the next statement in the batch.

In previous versions of Sql Server we use statement like below to drop the Database if exists.

IF DB_ID('SqlHintsDemoDB') IS NOT NULL
BEGIN
    DROP DATABASE SqlHintsDemoDB
END

You can go through the article How to check if a Database exists to see various options in the previous versions of Sql Server to check for the existence of a Database.

[ALSO READ]:

Native JSON Support in Sql Server 2016

Native JSON (Java Script Object Notation) support is one of the new feature that is coming with Sql Server 2016.

Introduction to JSON

JSON is simple data representation format, which readable, portable and platform independent. Now JSON is a popular lightweight data-exchange format between the systems. Prior to JSON, web Services used XML as their primary data format for data-interchange. Now JSON is the preferred data-interchange format used by the Web APIs. To know more on JSON you can visit http://json.org/

JSON Anatomy
JSON Structure

  • JSON Notations
    : JSON Property Name and value (if it is string) is enclosed within double quotes
    : : Colon symbol is used as the separator between the JSON property Name and Value.
    {} : Curly braces symbol represents the objects
    [,] : Arrays of Value
    [{},{}] : Arrays of Objects
  • To know more on JSON you can visit http://json.org/

    JSON In Sql Server 2016

    JSON implementation in Sql server is on the similar lines as that of XML. One major difference is: JSON doesn’t have native JSON data type like the XML data type. We can store JSON data in regular NVARCHAR/VARCHAR column.

    Below are the main JSON features introduced in Sql Server 2016. Click on the link to understand each of these features with an extensive list of examples.

    FOR JSON Clause: can be used to convert the query result (rows) to JSON format.

    OPENJSON Function : is very much similar to the OPENXML function, it provides a rowset view of the JSON. It is basically a table valued function, that can be used to transform the JSON value to one or many rows

    ISJSON Function: This function validates whether the parameter supplied to it is a well formed JSON or not

    JSON_VALUE Function: This function returns the scalar value from the input JSON text from the specified JSON path location

    JSON_QUERY Function: This function extracts the JSON fragment (i.e. JSON object or an array) from the input JSON string from the specified JSON path.

    JSON_MODIFY Function: This function can be used to update the value of the property in a JSON string and returns the updated JSON string.

    Indexing Strategy for JSON Value in Sql Server 2016

    lax and strict JSON Path modes in Sql Server 2016

    [ALSO READ]:

    New features in SQL SERVER 2016

    Data Paging by OFFSET…FECTCH and CTE – Sql Server

    When we have huge result set it doesn’t make sense to return the complete result set to the application and leave it to the datagrid, gridview or any other data control to handle the data paging. Because it wastes lot of network resources, puts pressure on the database server and the application server, so it makes page loading very slow. In such scenario it makes sense to return only the rows which needs to displayed on the current page, when user clicks next page/next result set then bring the next set of rows. In this way it reduces the unnecessary network traffic and load on the data base server, which in-turn helps in faster loading of the page.

    With Sql Server 2012 Microsoft has introduced OFFSET and FETCH feature for data paging. Prior to Sql Server 2012 CTE was on of the option for data paging.

    To demonstrate data paging let us create a customers table as shown in the below image by the following script:

    Data Paging Using CTE
    Script:

    --Create Demo database
    CREATE DATABASE SqlHintsCTEDataPaging
    GO
    USE SqlHintsCTEDataPaging
    GO
    -- Create an Customers table.
    CREATE TABLE dbo.Customers
    ( Id INT  PRIMARY KEY, FirstName NVARCHAR(50),
      LastName NVARCHAR(50))
    -- Populate Customer table with sample data
    INSERT INTO dbo.Customers VALUES
     (1, 'Basavaraj', 'Biradar') ,(2, 'Abhishiek', 'Akkanna')
    ,(3, 'Santosh', 'Patil'), (4, 'Sachin', 'Tendulkar')
    ,(5, 'Virendra', 'Shewag'),(6, 'Virat', 'Kohli')
    ,(7, 'Ajinkya', 'Rahane'), (8,'Cheteshwar', 'Pujara')

    Data Paging by OFFSET/FETCH

    We can write a stored procedure like below for Data Paging by using the OFFSET..FETCH pagination feature introduced in Sql Server 2012. This stored procedure gives specified number of rows (i.e. it can be specified by the parameter @pageSize) for the passed page number (i.e. parameter @pageNum) sorted by the FirstName column.

    CREATE PROCEDURE dbo.GetCustomersPagedDatabyFetch
    (
      @pageNum INT,
      @pageSize INT
    )
    AS
    BEGIN
    	SELECT Id, FirstName, LastName
    	FROM dbo.Customers WITH(NOLOCK)
    	ORDER BY FirstName
    	OFFSET (@pageNum - 1) * @pageSize ROWS
    	FETCH NEXT @pageSize ROWS ONLY  
    END

    Try to get the first page data sorted by FirstName by executing the above Stored Procedure, assume that the page size as 3 for our example.

    EXEC dbo.GetCustomersPagedDatabyFetch 
             @pageNum = 1, @pageSize = 3
    

    RESULT:
    Data Paging by OFFSET and FETCH Page 1

    Now try to get the second page data sorted by FirstName by executing the below statement.

    EXEC dbo.GetCustomersPagedDatabyFetch 
             @pageNum = 2, @pageSize = 3
    

    RESULT:
    Data Paging by OFFSET and FETCH Page 2

    Now try to get the third page data sorted by FirstName by executing the below statement.

    EXEC dbo.GetCustomersPagedDatabyFetch 
             @pageNum = 3, @pageSize = 3
    

    RESULT:
    Data Paging by OFFSET and FETCH Page 3

    The reason we got only two records in the above result even when the data page size 3 is, the demo Customers table created in this article has only 8 records. So, with page size as 3 the third page will have only two records.

    Data paging by CTE

    We can write a stored procedure like below for Data Paging by CTE. This stored procedure gives specified number of rows (i.e. it can be specified by the parameter @pageSize) for the passed page number (i.e. parameter @pageNum) sorted by the FirstName column.

    CREATE PROCEDURE dbo.GetCustomersPagedData
    (
    	@pageNum INT,  -- Data page number
    	@pageSize INT  -- Number of rows per page 
    )
    AS
    BEGIN
    	WITH PagingCTE AS
    	(
    	 SELECT Id, FirstName, LastName, 
              ROW_NUMBER() OVER (ORDER BY FirstName) AS RowNumber
    	 FROM dbo.Customers WITH(NOLOCK)
    	)
    	SELECT *
    	FROM PagingCTE
    	WHERE RowNumber BETWEEN (@pageNum - 1) * @pageSize + 1 
                  AND @pageNum * @pageSize	
    END

    Try to get the first page data sorted by FirstName by executing the above Stored Procedure, assume that the page size as 3 for our example.

    EXEC dbo.GetCustomersPagedData @pageNum = 1, @pageSize = 3
    

    RESULT:
    Data Paging by CTE

    Now try to get the second page data sorted by FirstName by executing the below statement.

    EXEC dbo.GetCustomersPagedData @pageNum = 2, @pageSize = 3
    

    RESULT:
    Data Paging by CTE data page 2

    Now try to get the third page data sorted by FirstName by executing the below statement.

    EXEC dbo.GetCustomersPagedData @pageNum = 3, @pageSize = 3
    

    RESULT:
    Data Paging by CTE data page 3

    The reason we got only two records in the above result even when the data page size 3 is, the demo Customers table created in this article has only 8 records. So, with page size as 3 the third page will have only two records.

    Data paging by CTE with dynamic Sort column

    In the previous example of this article the SP GetCustomersPagedData was supporting the data paging but the sort column here was always the FirstName column. But in real world we will always not have the data paging with sorting by just one column. For example, for the customers table we may need to support data paging with either FirstName or LastName as the sorting column. We can create a SP like below which supports the data paging by the FirstName or LastName as the sort column by using CTE:

    CREATE PROCEDURE dbo.GetCustomersDynamicSortColumn
    (
    	@pageNum INT,
    	@pageSize INT,
    	@sortColumnName VARCHAR(50)
    )
    AS
    BEGIN
      WITH PagingCTE AS
      (
        SELECT Id, FirstName, LastName, ROW_NUMBER() OVER 
         (ORDER BY CASE 
           WHEN @sortColumnName = 'FirstName' THEN  FirstName 
           WHEN @sortColumnName = 'LastName' THEN  LastName 
    						 END) AS RowNumber
        FROM dbo.Customers WITH(NOLOCK)
      )
      SELECT *
      FROM PagingCTE
      WHERE RowNumber BETWEEN (@pageNum - 1) * @pageSize + 1 
       AND @pageNum * @pageSize
    END
    

    Now try to execute the above stored procedure to get the first page data with page size as 3 and sort column as FirstName:

    EXEC dbo.GetCustomersDynamicSortColumn 
          @pageNum = 1, @pageSize = 3, @sortColumnName = 'FirstName'
    

    RESULT:
    Data Paging by CTE dynamic Sort Column

    Now execute the following statement to get the first page data with page size as 3 and sort column as LastName:

    EXEC dbo.GetCustomersDynamicSortColumn 
          @pageNum = 1, @pageSize = 3, @sortColumnName = 'LastName'
    

    RESULT:
    Data Paging by CTE dynamic Sort Column 2