SQL使用表中的#table / Temp表值函数

时间:2017-08-10 05:20:39

标签: sql sql-server stored-procedures user-defined-functions temp-tables

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

但是当我在函数旁边使用#tables时会出现以下错误

  

Msg 2772,Level 16,State 1,Procedure WeekNumbersWithinRange,Line 19
  无法从函数中访问临时表。

这是我的功能。

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

还有其他办法吗?或者我是否需要在存储过程中编写此逻辑?

2 个答案:

答案 0 :(得分:1)

您不能在UDF中使用Temp表,因为

  

无法在UDF中创建对象。

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

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

答案 1 :(得分:0)

我通常会选择永久保留Calendar表格,然后填充数百年的行。然后只是查询它。

但是,如果你拥有来拥有这个功能,你可以编写它来使用CTE并避免任何明确的状态/迭代管理:

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的值。

根据您使用的范围,您可能必须将MAXRECURSION选项应用于查询以允许CTE完全正常工作。