请参阅我先前的问题here-在SQL Server Management Studio中执行时效果很好,当我尝试在C#中执行时,我一直得到A TOP N或FETCH行计数值可能不是负错误。实体框架的代码。我使用的代码是;
var sDate = "20180925"; // DateTime.Now.AddMonths(NoOfMonthsBack).ToString("yyyyMMdd");
var eDate = "20180101"; //DateTime.Now.ToString("yyyyMMdd");
var result = ctx.Database.ExecuteSqlCommand("; WITH d(d) AS ( SELECT DATEADD(MONTH, n, DATEADD(MONTH, DATEDIFF(MONTH, 0, @StartDate), 0)) " +
"FROM ( SELECT TOP (DATEDIFF(MONTH, @StartDate, @EndDate) + 1) n = ROW_NUMBER() OVER (ORDER BY [object_id]) - 1 FROM sys.all_objects " +
"ORDER BY [object_id] ) AS n ) SELECT [Period] = CONVERT(VARCHAR(4), YEAR(d.d)) + '-' + CONVERT(VARCHAR(2), MONTH(d.d)), QtyTotal = ISNULL(SUM(o.QEXIT),0) " +
"FROM d LEFT OUTER JOIN VE_STOCKTRANS AS o ON o.TRANSDATE >= d.d and STOCKID = @pID AND TRANSTYPE = @TransType AND o.TRANSDATE < DATEADD(MONTH, 1, d.d) " +
"GROUP BY d.d ORDER BY d.d;",
new SqlParameter("@StartDate", sDate),
new SqlParameter("@EndDate", eDate),
new SqlParameter("@pID", pID),
new SqlParameter("@TransType", transType));
如果有经验的人可以向我展示正确的方向以解决此问题,我将不胜感激。
谢谢。
答案 0 :(得分:2)
SELECT TOP (DATEDIFF(MONTH, @StartDate, @EndDate) + 1)
给出了否定的答案,或者有可能这样做
用abs()
括起来以确保为正数:
SELECT TOP abs(DATEDIFF(MONTH, @StartDate, @EndDate)) + 1
答案 1 :(得分:2)
看起来NoOfMonthsBack
是一个正值(例如int
或float
)。如果您的目标是回到过去,则应否定使用它。在第一行的注释中:
var sDate = DateTime.Now.AddMonths(-NoOfMonthsBack).ToString("yyyyMMdd");