似乎多余,但我试图计算过程中临时创建的表中的行。
(注意:表格很可能编码错误)需要计算@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)
答案 0 :(得分: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')