Category Archives: Scripts

How to get Daily data in Sql Server

This article demonstrate how to get daily data in Sql Server in different formats as shown in the below image. Here Sales table data is presented in two different daily aggregated sales data formats.

Daily data report in Sql Server

Let us create a Sales table and insert 1000 Sample Sales Records With Random sales date in the past 5 days using the below script.

CREATE DATABASE SqlHintsDailyData
GO
USE SqlHintsDailyData
GO
--Create Temporary Sales Table
CREATE TABLE #Sales
(SalesId INT IDENTITY(1,1), SalesDate DateTime)
GO
--Populate 1000 Sample Sales Records With 
--Random past 0-5 days as sales date
INSERT INTO #Sales(SalesDate)
VALUES(DATEADD(DAY, - ROUND(5 * RAND(), 0),GETDATE()))
GO 1000

Demo 1: Getting Daily Data by using Group By

SELECT CAST(SalesDate AS DATE) [Date], 
   Count(1)  [Sales Count]   
FROM #Sales
GROUP BY CAST(SalesDate AS DATE)
ORDER BY 1 

RESULT:
Daily Data in Sql Server by Group By

Demo 2: Getting Daily data using Static PIVOT

[ALSO READ] PIVOT and UNPIVOT in Sql Server

SELECT *
FROM (SELECT CAST(SalesDate AS DATE) [Date], 
             Count(1)  [Sales Count]   
      FROM #Sales
      GROUP BY CAST(SalesDate AS DATE)) AS DailyData
PIVOT( SUM([Sales Count])  
    FOR [Date] IN ([2015-06-29],[2015-06-30],[2015-07-01],
  [2015-07-02],[2015-07-03],[2015-07-04])) AS DatePivot

RESULT:
Daily Data in Sql Server by Pivot

Demo 3: Getting Daily data using Dynamic PIVOT

[ALSO READ] Dynamic PIVOT in Sql Server

Problem with Demo 2 approach is , it is using the static PIVOT to get the data. Which requires the developer to specify all the dates as the pivot columns manually. We can re-write the Demo 2 examples by using Dynamic pivot approach as below which doesn’t require the developer to manually specify the dates column.

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

SELECT CAST(SalesDate AS DATE) [Date], Count(1)  [Sales Count] 
	INTO #PivotSalesData  
FROM #Sales
GROUP BY CAST(SalesDate AS DATE)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME([Date])
FROM (SELECT DISTINCT [Date] FROM #PivotSalesData) AS Dates
 
--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT ' + @ColumnName + '
    FROM #PivotSalesData
    PIVOT(SUM( [Sales Count]   ) 
          FOR [Date] IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

RESULT:
Daily Data in Sql Server by Pivot
[ALSO READ]:
How to get Yearly data in Sql Server
How to get Quarterly Data in Sql Server
How to get Monthly Data in Sql Server
How to get Hourly data in Sql Server

How to get Hourly data in Sql Server

This article demonstrate how to get hourly data in Sql Server in different formats as shown in the below image. Here Sales table data is presented in two different hourly aggregated sales data formats.

Hourly Sales Data in Sql Server

Let us create a Sales table and insert 1000 Sample Sales Records With Random sales date in the past 60 hours using the below script.

CREATE DATABASE SqlHintsHourlyData
GO
USE SqlHintsHourlyData
GO
--Create Temporary Sales Table
CREATE TABLE #Sales
(SalesId INT IDENTITY(1,1), SalesDate DateTime)
GO
--Populate 1000 Sample Sales Records With
--Random past 0-60 hours as sales date
INSERT INTO #Sales(SalesDate)
VALUES(DATEADD(hh, - ROUND(60 * RAND(), 0),GETDATE()))
GO 1000

Demo 1: Getting Hourly Data using Group By

SELECT CAST(SalesDate AS DATE) [Date], 
    DATEPART(hour,SalesDate) [Hour], Count(1)  [Sales Count]   
FROM #Sales
GROUP BY CAST(SalesDate AS DATE), DATEPART(hour,SalesDate)
ORDER BY 1 ,2

RESULT:
Hourly Data Sql Script

Demo 2: Getting Hourly Data using Static PIVOT

[ALSO READ] PIVOT and UNPIVOT in Sql Server
Format 1: Dates as column

SELECT *
FROM (SELECT CAST(SalesDate AS DATE) [Date], 
   DATEPART(hour,SalesDate) [Hour], Count(1)  [Sales Count]   
   FROM #Sales
   GROUP BY CAST(SalesDate AS DATE), 
         DATEPART(hour,SalesDate)) AS HourlySalesData
PIVOT( SUM([Sales Count])   
  FOR [Date] IN ([2015-07-01], [2015-07-02], 
  [2015-07-03])) AS DatePivot

RESULT:
Hourly Data in Sql by using Static Pivot
Format 2: Hours as column

SELECT *
FROM (SELECT CAST(SalesDate AS DATE) [Date], 
   DATEPART(hour,SalesDate) [Hour], Count(1)  [Sales Count]   
   FROM #Sales
   GROUP BY CAST(SalesDate AS DATE), 
         DATEPART(hour,SalesDate)) AS HourlySalesData
PIVOT( SUM([Sales Count])   
  FOR [Hour] IN ([0], [1], [2], [3], [4], [5], [6], [7],
     [8], [9], [10],[11], [12], [13], [14], [15], [16], 
	 [17], [18], [19], [20], [21], [22], [23])) AS DatePivot

RESULT:
Hourly Data in Sql by Dynamic Pivot

Demo 3: Getting Hourly Data using Dynamic PIVOT

[ALSO READ] Dynamic PIVOT in Sql Server

Problem with Demo 2 approach is , it is using the static PIVOT to get the data. Which requires the developer to specify all the dates or hours as the pivot columns manually. We can re-write the Demo 2 examples by using Dynamic pivot approach as below which doesn’t require the developer to manually specify the dates/hours column.

Format 1: Dates as column

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

SELECT CAST(SalesDate AS DATE) [Date], 
   DATEPART(hour,SalesDate) [Hour], Count(1)  [Sales Count]   
	INTO #PivotSalesData
FROM #Sales
GROUP BY CAST(SalesDate AS DATE), DATEPART(hour,SalesDate)
--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME([Date])
FROM (SELECT DISTINCT [Date] FROM #PivotSalesData) AS Dates
--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT [Hour], ' + @ColumnName + '
    FROM #PivotSalesData
    PIVOT(SUM( [Sales Count]   ) 
          FOR [Date] IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

RESULT:
Hourly Data in Sql by using Static Pivot
Format 2: Hours as column

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT CAST(SalesDate AS DATE) [Date], 
   DATEPART(hour,SalesDate) [Hour], Count(1)  [Sales Count]   
	INTO #PivotSalesData
FROM #Sales
GROUP BY CAST(SalesDate AS DATE), DATEPART(hour,SalesDate)
--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME([Hour])
FROM (SELECT DISTINCT [Hour] FROM #PivotSalesData) AS Dates
--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT [Date], ' + @ColumnName + '
    FROM #PivotSalesData
    PIVOT(SUM( [Sales Count]   ) 
          FOR [Hour] IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

RESULT:
Hourly Data in Sql by Dynamic Pivot

[ALSO READ]:
How to get Yearly data in Sql Server
How to get Quarterly Data in Sql Server
How to get Monthly Data in Sql Server
How to get Daily data in Sql Server

How to check if a VIEW exists in Sql Server

Many a times we come across a scenario where we need to execute some code based on whether a View exists or not. There are different ways of identifying the View existence in Sql Server, this article will list out the commonly used approaches. Let me know which approach you use and reason for the same.

[ALSO READ] Views in Sql Server

To demonstrate these different approaches let us create a sample database SqlHintsDemoDB. Create Customers Table with sample data and a vwGetCustomerInfo View by the following script:

CREATE DATABASE SqlHintsDemoDB
GO
USE SqlHintsDemoDB
GO
--Create Customer table
CREATE TABLE dbo.Customers
( CustomerID int Identity(1,1), FirstName NVarchar(50),
  LastName NVarChar(50), Phone varchar(50))
GO
--Insert sample records into the customer table
INSERT INTO Customers (FirstName, LastName, Phone)
Values ('Kalpana','Biradar','2727272727'),
       ('Basavaraj','Biradar','1616161616')
GO
--Create view
CREATE VIEW dbo.vwGetCustomerInfo
AS
 SELECT CustomerID, FirstName +' ' + LastName FullName
 FROM CUSTOMERS
GO
SELECT * FROM dbo.vwGetCustomerInfo
GO

[ALSO READ] How to check if a Table exists in Sql Server

Approach 1: Using sys.views catalog view

We can write a query like below to check if a view vwGetCustomerInfo exists in the current database in any schema.

IF EXISTS(SELECT 1 FROM sys.views 
     WHERE Name = 'vwGetCustomerInfo')
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-sys.views 1

The above query checks the existence of the vwGetCustomerInfo View across all the schemas in the current database. Instead of this if you want to check the existence of the View in a specified Schema then we can re-write the above query as below:

IF EXISTS(SELECT 1 FROM sys.views 
   WHERE object_id = OBJECT_ID('dbo.vwGetCustomerInfo'))
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-sys.views 2

If you want to check the existence of a View in a database other than the current contextual database, then we can re-write the above query as shown below:

IF EXISTS(SELECT 1 FROM SqlHintsDemoDB.sys.views 
   WHERE object_id = OBJECT_ID('dbo.vwGetCustomerInfo'))
	BEGIN
		PRINT 'View Exists'
	END
GO

RESULT:
Check-View-Existence-using-sys.views 3
[ALSO READ] How to check if a record exists in table

Approach 2: Using sys.objects catalog view

sys.views catalog view inherits the rows from the sys.objects catalog view, sys.objects catalog view is referred to as the base view whereas sys.views is referred to as derived view. sys.views will return the rows only for the views, whereas sys.objects view apart from returning the rows for Views, it returns rows for the objects like: tables, stored procedure etc.

We can write a script like below to check the existence of a view in the current contextual database:

IF EXISTS (SELECT * FROM sys.objects
            WHERE object_id = OBJECT_ID('dbo.vwGetCustomerInfo')
                    AND type = 'V') 
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-sys.objects

Approach 3: Using sys.sql_modules Catalog View

We can use the sys.sql_modules catalog view to check the existence of the View as shown below:

USE SqlHintsDemoDB
GO
IF EXISTS (SELECT 1 FROM sys.sql_modules
   WHERE object_id =  OBJECT_ID('dbo.vwGetCustomerInfo')
   AND OBJECTPROPERTY(object_id, 'IsView') = 1) 
	BEGIN
		PRINT 'View Exists'
	END

RESULT
Check-View-Existence-using-sys.sql_modules

Approach 4: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if the View vwGetCustomerInfo exists in the current database.

IF OBJECT_ID(N'dbo.vwGetCustomerInfo', N'V') IS NOT NULL
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-Object_Id function

Specifying the Database Name and Schema Name parts for the View Name is optional. But specifying Database Name and Schema Name provides an option to check the existence of the View in the specified database and within a specified schema, instead of checking in the current database across all the schemas. The below query shows that, even though the current database is MASTER database, we can check the existence of the view vwGetCustomerInfo in the dbo schema in the SqlHintsDemoDB database.

USE master	
GO
IF OBJECT_ID(N'SqlHintsDemoDB.dbo.vwGetCustomerInfo', 
                  N'V') IS NOT NULL
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-Object_Id function 2

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.views/sys.sql_modules instead of sys.sysobjects system table directly to check the existence of the View.

USE SqlHintsDemoDB
GO
IF EXISTS(SELECT 1 FROM sys.sysobjects  
     WHERE id = OBJECT_ID(N'dbo.vwGetCustomerInfo') 
                      AND xtype=N'V')
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-sys.sysobjects

[ALSO READ] :
How to check if a Database exists
How to check if a Table exists
How to check if a Stored Procedure exists in Sql Server
How to check if Temp table exists
How to check if a record exists in table