如何在SSRS中执行execute(@variable)(或者甚至可以这样做)

时间:2013-11-25 16:18:38

标签: sql-server reporting-services

我在SQL Server Management Studio中创建了这个SQL:

Select @query =  'Select LastName, FirstName, ' + @weekNumbersNull + '
from (
             Select LastName, FirstName, Hours, ''Week'' + 
             Case When DatePart(Weekday, Date) = 1 
             Then Cast(DatePart(ww, Date - 6) as nvarchar(max))
             Else Cast(DatePart(ww, Date - DatePart(Weekday, Date) + 2) as nvarchar(max))
             End WeekNo
             From Entry
             Where Date between ''11/1/2013'' and ''11/30/2013'') alpha
             pivot (
             sum(Hours)
             for WeekNo in (' + @weekNumbers + ')
             ) p 
             order by LastName, FirstName'
execute(@query)

(我省略了为简洁定义所有变量的SQL) 当我在那里运行时,我得到了结果。所以,我将这个SQL移植到SSRS并在数据集下,我只看到我给数据集的名称没有列:

enter image description here

有没有办法让它在SSRS中运行,或者我是否需要寻找其他方法才能使其工作?

谢谢!

2 个答案:

答案 0 :(得分:0)

如果动态定义SSRS数据集字段,您将面临艰难的战斗。根据您的要求,我会尝试确定要返回的一些固定的列名称,并始终返回那些,无论是否有数据。

使动态SQL运行不会是一个大问题。这是返回的字段的动态性质,将抛出SSRS。 (固定列名称也将使报告更容易设计。)

如果不了解您的要求的详细信息,很难说,但看起来您在查询中尝试做的太多了;让SSRS完成一些工作:如果您删除了pivot功能,我怀疑您的查询在Matrix report中运行良好:您可以在SSRS中转移数据,并且每周都有单独的列报告层面。

答案 1 :(得分:0)

我找到了一个解决方案,并因此修改了我的SQL:

Declare @WeekStart DateTime
Declare @WeekEnd DateTime

Select @WeekStart = @DerivedStartDate
Select @WeekEnd = DateAdd("dd", 6, @WeekStart)

Create Table #TempTable (WeekOf DateTime, LastName nvarchar(max), FirstName nvarchar(max), Hours numeric)

While @WeekStart < @DerivedEndDate Begin
   Insert into #TempTable
   Select @WeekStart week, LastName, FirstName, 
      (
          Select sum(Hours) 
          From Entry x
          Where x.Date between @WeekStart and @WeekEnd and x.uuid = entry.uuid
       ) as TotalHours
   From Entry
   Where (
      Select sum(Entry2.Hours) From Entry as Entry2
      Where Entry2.UUID = Entry.UUID and Entry2.Date Between @WeekStart and @WeekEnd) < 40
   Or not exists 
   (
      Select 1 From Entry as Entry2
      Where Entry2.UUID = Entry.UUID and Entry2.Date Between @WeekStart and @WeekEnd
   )  
   Group By LastName, FirstName, uuid

   Select @WeekStart = DateAdd(dd, 1, @WeekEnd)
   Select @WeekEnd = DateAdd(dd, 7, @WeekEnd)
End

Select * from #TempTable
Order by WeekOf, LastName, FirstName
Delete #TempTable
Drop Table #TempTable

它就像一个魅力。