子查询内部的变量未接收变量值

时间:2013-04-04 16:00:29

标签: sql sql-server tsql

我之前从未尝试过将变量值传递给子查询,而且我似乎错了。我没有收到任何错误,但我也没有得到任何结果,而如果我硬编码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,@ Endate&的值@Role似乎没有进入子查询。我是否需要做一些事情来告诉潜水员在盒子外面看?

1 个答案:

答案 0 :(得分:1)

两个问题:

  1. 您没有为volStatus
  2. 分配值
  3. 应该是@volstatus而不是@ volstatus - 没有空格
  4. 所以,改变:

    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