-1

我有递归日期的sql查询错误问题

递归查询“日期”的“日历日期”列中的锚点和递归部分之间的类型不匹配。

";WITH Dates as ("
       + " SELECT @FromDate as CalendarDate "
       + " UNION ALL "
       + " SELECT dateadd(MONTH, 1, CalendarDate) AS CalendarDate "
       + " FROM Dates "
       + " WHERE DATEADD(MONTH, 1, CalendarDate) < @ToDate   )"
       + " ,cteMonthEnd AS    ( "
       + "  SELECT* , MonthEnd = DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, CalendarDate) + 1, 0)) "
       + "  FROM Dates    ) "
       + " SELECT CTE.CalendarDate, s.StrainId,GOH.CagePerDiem, "
       + " COUNT(CASE WHEN DATEDIFF(DAY, M.BirthDate, CTE.MonthEnd) >= 17  and M.DeathDate IS NULL  THEN 1 END) TotalKeptMicesOver17Days,"
       + " COUNT(CASE WHEN AnimalUseCd = 2 and DATEDIFF(DAY, M.BirthDate, CTE.MonthEnd) >= 17 and DeathDate IS NULL  THEN 1 END) BreedingKeptMices,"
       + " COUNT(CASE WHEN AnimalUseCd = 3 and DATEDIFF(DAY, M.BirthDate, CTE.MonthEnd) >= 17  and DeathDate IS NULL  THEN 1 END) ExperimentKeptMices,"
       + " COUNT(CASE WHEN AnimalUseCd = 0 and DATEDIFF(DAY, M.BirthDate, CTE.MonthEnd) >= 17  and DeathDate IS NULL  THEN 1 END) AvailableKeptMices,"
       + " COUNT(CASE WHEN AnimalUseCd = 2 and DATEDIFF(DAY, M.BirthDate, CTE.MonthEnd) >= 17  and GenderCd = 2   and DeathDate IS NULL  THEN 1 END) BreedingKeptFemaleCount,"
       + " COUNT(CASE WHEN AnimalUseCd = 2 and DATEDIFF(DAY, M.BirthDate, CTE.MonthEnd) >= 17  and GenderCd = 1   and  DeathDate IS NULL  THEN 1 END) BreedingKeptMaleCount,"
       + " COUNT(CASE WHEN AnimalUseCd = 3 and DATEDIFF(DAY, M.BirthDate, CTE.MonthEnd) >= 17  and GenderCd = 2   and  DeathDate IS NULL  THEN 1 END) ExperimentKeptFemaleCount,"
       + " COUNT(CASE WHEN AnimalUseCd = 3 and DATEDIFF(DAY, M.BirthDate, CTE.MonthEnd) >= 17  and GenderCd = 1   and  DeathDate IS NULL  THEN 1 END) ExperimentKeptMaleCount"
       + " FROM cteMonthEnd CTE"
       + " CROSS JOIN Strains S"
       + " JOIN Mice M ON M.StrainId = S.StrainId"
       + " LEFT JOIN GroupOverhead GOH on S.GroupId = GOH.GroupId"
       + " WHERE  S.GroupId in (Select GroupId from Groups where OrganizationId = @groupId)"
       + " GROUP BY S.StrainId, CalendarDate,GOH.CagePerDiem"
       + " order by CalendarDate asc";

这个查询已经在存储过程中执行了但是我们有这个代码的问题将在 c# 代码中合并我得到上面提到的错误

4

1 回答 1

0

您没有@FromDate在第一个结果集(锚点)的唯一列中指定数据类型。a 上的第SELECT一个UNION应该正确指定数据类型,这样您就不会遇到这种冲突问题。

将变量转换为正确的数据类型,例如DATE

SELECT CONVERT(DATE, @FromDate) as CalendarDate
UNION ALL --...
于 2019-01-04T12:09:26.320 回答