-1

似乎是多余的,但我试图在一个过程中计算一个临时创建的表中的行数。

(注意:表格很可能编码错误)@rows需要对变量进行计数,并且应该从变量中输出一年中的确切天数@StartDate。(这包括闰年)。

创建的表还应在变量INSERT之后VALUES的每一天准确地记录一年。@StartDate

此作业需要 TEMPORARY TABLE。对不起人们,但这是老师要求的。

仅供参考:我是新手,非常感谢您的帮助:)

CREATE PROCEDURE usp_DateLookup
    @StartDate DATE,
    @Rows INT OUTPUT

AS
    DECLARE @countIndex INT
    DECLARE @yearDate DATE
    DECLARE @todaysDate DATE
    SET @yearDate = DATEADD(YEAR, 1,@StartDate)
    SET @todaysDate = GETDATE()
    BEGIN

        CREATE TABLE #DateLookup
        (
        DateID INT IDENTITY (1,1),
        DateDescription DATE
        )

     WHILE (SELECT DATEDIFF(DD,@StartDate, @yearDate) FROM #DateLookup) <= 366   
     BEGIN
         SET @countIndex = @countIndex +1

        INSERT #DateLookup (DateDescription)
        VALUES (DAY(@todaysDate)+ @countIndex)

    END
    SET @Rows = (SELECT COUNT(DateDescription) FROM #DateLookup) 
END
GO


DECLARE @StartDate DATE
DECLARE @Rows INT

SET @StartDate = '2012-05-06'
EXEC usp_DateLookup @StartDate, @Rows OUTPUT
PRINT CONVERT(NVARCHAR,@Rows)
4

1 回答 1

1

我不确定你为什么需要#DateLookup桌子?您可以按如下方式获取一年中的天数(最好用作函数)

CREATE PROCEDURE usp_DateLookup
    @StartDate DATE,
    @Rows INT OUTPUT

AS
    --DECLARE @StartDate DATE = '2012-05-06'
    select @Rows = datediff(day,@StartDate,dateadd(year,1,@StartDate))

END
GO;

根据您的评论(您需要分配临时表),您可以在没有如下循环的情况下执行此操作;SQL-DEMO

CREATE PROCEDURE usp_DateLookup
    @StartDate DATE,
    @Rows INT OUTPUT

AS
    --DECLARE @StartDate DATE = '2012-05-06'
    DECLARE @Rows INT = DATEDIFF(day,@StartDate,dateadd(year,1,@StartDate))

    CREATE TABLE #DateLookup
    (
      DateID INT IDENTITY (1,1),
      DateDescription DATE
    )

    ;with Digits as (
    select Digit 
    from (
        values (0), (1), (2), (3), (4), (5), 
            (6), (7), (8), (9)) as t(Digit)),
    Numbers as (
        select u.Digit + t.Digit*10 +h.Digit*100  as Number
        from Digits u
        cross join Digits t
        cross join Digits h
    )
    insert into #DateLookup
    select  dateadd(day,Number+1,@StartDate) from Numbers where Number < @Rows 
    order by Number

END
GO;

你还需要一个循环吗?INSERT由于您尝试在字段中输入数字 ( DAY(@todaysDate)+ @countIndex) ,因此您失败了DATE

INSERT #DateLookup (DateDescription)
    VALUES ('this-should-be-a-valid-date')
于 2013-02-01T18:08:31.760 回答