0

我以前从未尝试将变量值传递给子查询,而且我似乎做错了。我没有收到任何错误,但也没有得到任何结果,而如果我将 startdate、enddate 和角色的值硬编码到子查询中,它会正确运行。

================编辑=======================

我的错,我发布了我正在玩的早期测试脚本,它确实充满了错误,对此感到抱歉。这是我正在使用的完整代码:

DECLARE @Role varchar,
    @StartDate datetime,
    @Enddate datetime;

SET     @Role = 'Volunteer';
SET     @StartDate = DATEADD(d, -100, getdate());
SET     @Enddate = getdate();

SELECT rolename, Category, [1] as [1 Day],[2] as [2 Days],[3] as [3 Days],[4] as [4 Days],[5] as [5 Days],[6] as [6 Days],[7] as [7 Days]  FROM
(SELECT    CriminalHistoryID, vps.RoleName, 'Rec2PreClr' as Category,
        DATEDIFF(d, chc.ReceiveDate, chc.PreClrDate) as DaysDif
  FROM  dbo.v_PersonStatus vps
              INNER JOIN dbo.CriminalHistoryCheck chc
                    ON vps.PersonID = chc.PersonID
  WHERE chc.ReceiveDate BETWEEN @StartDate AND @Enddate AND vps.rolename = @Role and DATEDIFF(d, chc.ReceiveDate, chc.PreClrDate) BETWEEN 0 and 7
  UNION
  SELECT      CriminalHistoryID, vps.RoleName, 'PreClr2Clr' as Category,
              DATEDIFF(d, chc.PreClrDate, chc.FinalDate) as DaysDif
  FROM  dbo.v_PersonStatus vps
              INNER JOIN dbo.CriminalHistoryCheck chc
                    ON vps.PersonID = chc.PersonID
  WHERE chc.ReceiveDate BETWEEN @StartDate AND @Enddate AND vps.rolename = @Role AND DATEDIFF(d, chc.PreClrDate, chc.FinalDate) BETWEEN 0 and 7
  UNION
  SELECT      CriminalHistoryID, vps.RoleName, 'Rec2Clr' as Category,
              DATEDIFF(d, chc.ReceiveDate, FinalDate) as DaysDif
  FROM  dbo.v_PersonStatus vps
              INNER JOIN dbo.CriminalHistoryCheck chc
                    ON vps.PersonID = chc.PersonID
  WHERE chc.ReceiveDate BETWEEN @StartDate AND @Enddate AND vps.rolename = @Role AND DATEDIFF(d, chc.ReceiveDate, FinalDate) BETWEEN 0 and 7
  ) UNIONqry
PIVOT
(count(CriminalHistoryID) for DaysDif in ([1],[2],[3],[4],[5],[6],[7])) pvt
Order by RoleName, Category

@Startdate、@Enddate 和 @Role 的值似乎没有进入子查询。我是否需要做一些事情来告诉潜艇在盒子外面看?

4

1 回答 1

1

两个问题:

  1. 您没有为 volStatus 赋值
  2. 它应该是@volstatus而不是@ volstatus- 没有空间

所以,改变:

WHERE chc.ReceiveDate BETWEEN @StartDate AND @Enddate AND vps.rolename = @ VolStatus and DATEDIFF(d, chc.ReceiveDate, chc.PreClrDate) BETWEEN 0 and 7

至:

WHERE chc.ReceiveDate BETWEEN @StartDate AND @Enddate AND vps.rolename = @VolStatus and DATEDIFF(d, chc.ReceiveDate, chc.PreClrDate) BETWEEN 0 and 7
于 2013-04-04T16:06:48.680 回答