Monday 18 July 2016

SQLSERVER Stored Procedure Dynamic Query Pivot Table DateTime parameter

 USE [TNG_KMS]  
 GO  
 /****** Object: StoredProcedure [dbo].[SP_S_GetCompletedInjectionReport]  Script Date: 18/7/2016 10:52:36 AM ******/  
 SET ANSI_NULLS ON  
 GO  
 SET QUOTED_IDENTIFIER ON  
 GO  
 DROP PROCEDURE [dbo].[SP_S_GetCompletedInjectionReport]  
 GO  
 CREATE PROCEDURE [dbo].[SP_S_GetCompletedInjectionReport]  
 --(       
 --     -- Add the parameters for the stored procedure here  
      @dt_DateFrom datetime ,   
      @dt_DateTo datetime  
 --)  
 AS  
 BEGIN  
      -- SET NOCOUNT ON added to prevent extra result sets from  
      -- interfering with SELECT statements.  
      SET NOCOUNT ON;  
      SET FMTONLY OFF;  
   -- Insert statements for procedure here  
 DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)  
 DECLARE @ColumnName AS NVARCHAR(MAX)  
 SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(name)  
 FROM (select name from LookupItems where CategoryID=4) AS AppSector  
 ORDER BY name  
 SET @DynamicPivotQuery =  
 'SELECT * FROM (  
   select   
      @@ROWCOUNT No,      FormRefNo,   
      ISNULL(TotalSam,0) BigTotalSam,   
      R.CreatedTime,R.CompletionDate,  
       Datediff(dd,CONVERT(Date,R.CreatedTime),R.CompletionDate) ''DaysCompleted'',  
      LI.Name [AppSector]  
      from   
       [TNG_KMS].[dbo].[Request] R,   
       [TNG_KMS].[dbo].[ProfileGroup] PG,  
       [TNG_KMS].[dbo].[LookupItems] LI  
       where R.ProfileGroupID=PG.ID  
       and PG.AppSectorID=LI.ItemIndex   
       and LI.CategoryID = 4  
       and R.RequestStatusID=5  
       and (R.CompletionDate between @dt_DateFrom and @dt_DateTo)  
 ) as s  
 PIVOT  
 (  
   SUM(BigTotalSam) FOR [AppSector] IN (' +@ColumnName+ ')  
 ) AS pvt'  
 ;  
 --Execute the Dynamic Pivot Query  
 EXEC sp_executesql @DynamicPivotQuery,        
                          N'@dt_DateFrom DATETIME, @dt_DateTo DATETIME',  
                          @dt_DateFrom,   
                          @dt_DateTo;   
 END  
 GO  

No comments: