SQL 在 table 值函数中使用 #table/ Temp table

SQL using #table/ Temp table inside a table valued function

我需要一个函数来获取给定日期范围内的所有周数。 我必须将它与我的存储过程分开,因为它有一个漫长的过程。

但是当我在函数中使用#tables 时,它给出了以下错误

Msg 2772, Level 16, State 1, Procedure WeekNumbersWithinRange, Line 19
Cannot access temporary tables from within a function.

这是我的功能。

CREATE FUNCTION WeekNumbersWithinRange
(   
    @FromDate DATETIME,
    @ToDate DATETIME
)
RETURNS TABLE 
AS
BEGIN
    IF OBJECT_ID (N'tempdb..#WeeksofRange', N'U') IS NOT NULL
    BEGIN
        DROP TABLE #WeeksofRange
    END

    CREATE TABLE #WeeksofRange (WeekNo  INT);

    -- Get all week numbers for the given delivery date range
    IF OBJECT_ID (N'tempdb..#Calendar', N'U') IS NOT NULL
    BEGIN
        DROP TABLE #Calendar
    END

    CREATE TABLE #Calendar
    (
         CalendarDate DATE PRIMARY KEY,
         IsWeekend BIT, 
         YearNo SMALLINT, 
         QuarterNo TINYINT, 
         MonthNo TINYINT,
         DayOfYearNo SMALLINT, 
         DayNo TINYINT, 
         WeekNo TINYINT, 
         WeekDayNo TINYINT
    )

    DECLARE @beginDate DATE, @endDate DATE

    SELECT 
        @beginDate = @FromDate, @endDate = @ToDate

    WHILE @beginDate <= @endDate 
    BEGIN
        INSERT INTO #Calendar (CalendarDate, IsWeekend, YearNo, QuarterNo, MonthNo, DayOfYearNo, DayNo, WeekNo, WeekDayNo)
            SELECT
                @beginDate As CalendarDate,
                (CASE WHEN DATEPART(Weekday, @beginDate) IN (7, 1) 
                         THEN 1 ELSE 0 
                 END) AS IsWeekend,
                DATEPART(Year, @beginDate) AS YearNo,
                DATEPART(QUARTER, @beginDate) AS QuarterNo,
                DATEPART(MONTH, @beginDate) AS MonthNo,
                DATEPART(DayOfYear, @beginDate) AS DayOfYearNo, 
                DATEPART(Day, @beginDate) AS DayNo,
                DATEPART(Week, @beginDate) AS WeekNo,
                DATEPART(WEEKDAY, @beginDate) AS WeekDayNo
                --,(Case When @beginDate < '02/03/2011' Then 0 Else DATEPART(Week,  @beginDate) - 5 End) As mySpecificWeekNo

        SET @beginDate = DATEADD(Day, 1, @beginDate)
    END

    INSERT INTO #WeeksofRange
        SELECT DISTINCT WeekNo 
        FROM #Calendar;

    -- End of Select all week numbers in the range

    SELECT * FROM #WeeksofRange
GO

还有其他方法吗?或者我需要在我的存储过程中编写这个逻辑吗?

您不能在 UDF 中使用临时 table,因为

the object can't be created inside UDF.

不要使用 Temp table,而是使用 table 变量,这应该可以解决您的问题

CREATE FUNCTION WeekNumbersWithinRange
(   
    @FromDate DATETIME,
    @ToDate DATETIME
)
RETURNS TABLE 
AS
BEGIN

DECLARE @WeeksofRange TABLE 
(
WeekNo  INT
)

-- Get all week numbers for the given delivery date range

declare @Calendar table
(CalendarDate Date Primary key, IsWeekend Bit, YearNo SmallInt, QuarterNo TinyInt, MonthNo TinyInt, DayOfYearNo SmallInt, DayNo TinyInt, WeekNo TinyInt, WeekDayNo TinyInt )

Declare @beginDate Date, @endDate Date


Select @beginDate = @FromDate , @endDate = @ToDate


While @beginDate <= @endDate 
Begin
 Insert Into @Calendar (CalendarDate, IsWeekend, YearNo, QuarterNo, MonthNo, DayOfYearNo, DayNo, WeekNo, WeekDayNo)

 Select
  @beginDate As CalendarDate  
  ,(Case When DATEPART(Weekday, @beginDate) In (7, 1) Then 1 Else 0 End) As IsWeekend 
  ,DATEPART(Year, @beginDate) As YearNo 
  ,DATEPART(QUARTER, @beginDate) As QuarterNo 
  ,DATEPART(MONTH, @beginDate) As MonthNo 
  ,DATEPART(DayOfYear, @beginDate) As DayOfYearNo 
  ,DATEPART(Day, @beginDate) As DayNo   
  ,DATEPART(Week, @beginDate) As WeekNo
  ,DATEPART(WEEKDAY, @beginDate) As WeekDayNo 
  --,(Case When @beginDate < '02/03/2011' Then 0 Else DATEPART(Week, @beginDate) - 5 End) As mySpecificWeekNo
 Set @beginDate = DateAdd(Day, 1, @beginDate)
End

INSERT INTO @calendar
SELECT DISTINCT WeekNo FROM @Calendar;

-- End of Select all week numbers in the range


SELECT * FROM @WeeksofRange

GO

我通常会选择使 Calendar table 永久化并填充它,比如说,一个世纪的行。然后查询就可以了。

但是,如果您拥有此功能,您可以编写它以使用 CTE 并避免任何显式 state/iteration 管理:

CREATE FUNCTION WeekNumbersWithinRange
(   
    @FromDate DATETIME,
    @ToDate DATETIME
)
RETURNS TABLE 
AS
    return (With Weeks as (
        select DATEPART(week,@FromDate) as Week,@FromDate as dt
        union all
        select DATEPART(week,ndt),ndt
        from Weeks
            cross apply (select DATEADD(day,7,dt) as ndt) t
        where
            ndt < @ToDate
    )
    select Week from Weeks
    union
    select DATEPART(week,@ToDate)
    )

我做了一个简化假设,即周数仅每 7 天更改一次,因此我们不需要在 CTE 中为每一天生成一行。另外,我使用最后的 UNION 来确保包括最后一周。它 可以 被跳过,因为我以 7 天为增量工作,所以我们可以将我们的值从前一周直接跳到大于 @ToDate.[=15= 的值]

根据您使用的范围,您可能必须将 MAXRECURSION 选项应用到查询以允许 CTE 充分工作。