我已经创建了SQL函数来获取我的Gridview中的日期,所以我将开始日期和结束日期传递给我的函数但是收到如下错误。
The maximum recursion 100 has been exhausted before statement completion
如果计数日期大于100表示出现上述错误,如果低于100个日期表示没有收到任何错误。我有超过100天的记录。
以下是我的数据逻辑。
public DataTable GetDates(DateTime StartDate, DateTime EndDate)
{
DataTable dt = new DataTable();// order by dt desc
ConnectMethod();
cmd = new SqlCommand("select dt from dbo.ExplodeDates(@StartDate,@EndDate) order by dt desc", con);
try
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@StartDate", StartDate);
cmd.Parameters.AddWithValue("@EndDate", EndDate);
cmd.ExecuteScalar();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
catch (Exception ex)
{ return dt; }
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}
}
我在cmd.ExecuteScalar()上收到此错误;线。 下面是我的SQL函数。
CREATE FUNCTION [dbo].[ExplodeDates](
@startdate datetime
, @enddate datetime
)
RETURNS TABLE
AS
RETURN
WITH DATES AS(
SELECT @startdate AS dt
UNION ALL
SELECT DATEADD(D, 1, dt) FROM DATES WHERE DT<@enddate
)
SELECT * FROM DATES
GO
请从上午开始帮助解决这个问题。
答案 0 :(得分:2)
您可以使用简单的 tally-table-on-the-fly 来避免递归CTE:
DECLARE @NumberOfDays INT=200;
DECLARE @StartDate DATE=GETDATE();
WITH Numbers AS
(SELECT TOP (@NumberOfDays) ROW_NUMBER() OVER(ORDER BY (SELECT NULL))-1 AS Nmbr FROM master..spt_values)
SELECT DATEADD(DAY,Nmbr,@StartDate)
FROM Numbers
master..spt_values
应包含足够的行(~2500)以确保返回200行。您可以使用CROSS JOIN master..spt_values AS v2
轻松扩大此数字,这将允许相当大的数字......(超过6十亿)
CREATE FUNCTION [dbo].[ExplodeDates]
(
@startdate datetime
, @enddate datetime
)
RETURNS TABLE
AS
RETURN
WITH Numbers AS
(SELECT TOP (DATEDIFF(DAY,@startdate,@enddate)+1) ROW_NUMBER() OVER(ORDER BY (SELECT NULL))-1 AS Nmbr FROM master..spt_values)
SELECT DATEADD(DAY,Nmbr,@startdate) AS dt
FROM Numbers;
GO
SELECT * FROM dbo.ExplodeDates({d'2017-03-01'},GETDATE());
答案 1 :(得分:0)
您需要在选择表后添加maximum recursion
选项。喜欢:
from DATES
option (maxrecursion 0)