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  

Wednesday 13 July 2016

Fixed: The selected stored procedure returns no columns

Hi johnjohn123123, The problem maybe caused by your stored procedures may contain: Dynamic queries Temporary tables While EF doesn't support importing stored procedures above. The reason is that to import the procedure EF must execute it. Such operation can be dangerous because it can trigger some changes in the database I suggest you add following code in the start of your stored procedure SET FMTONLY OFF then save the Stored Procedure, Update the model and retry. Hope it can help you. Best Regards, Kevin Shen.