我的任务是创建表值函数,它将有一个DATETIME参数,并返回该月的第一天到最后一天的每个日期,例如我从该参数给出了函数日期04/12/2015将打印12月的所有31天。
我已经创建了2个标量函数(这是分配中的提示),第一天计算
CREATE FUNCTION firstday
(
@first DATETIME
)
RETURNS DATETIME
AS
BEGIN
RETURN CAST(MONTH(@first) AS VARCHAR) + '/' + '01/' + + CAST(YEAR(@first) AS VARCHAR)
END
,第二天计算最后一天:
CREATE FUNCTION lastday
(
@last DATETIME
)
RETURNS DATETIME
AS
BEGIN
RETURN CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@last))),DATEADD(mm,1,@last)),101)
END
这里是表值函数,但我不知道如何在其中使用那些标量函数
CREATE FUNCTION get_months_dates
(
@mydate DATETIME
)
RETURNS TABLE
AS
RETURN
WITH Calender AS
(
SELECT **first_function** AS CalenderDate
UNION ALL
SELECT CalenderDate + 1 FROM Calender
WHERE CalenderDate + 1 <= **last_function**
)
SELECT [Date] = CONVERT(VARCHAR(10),CalenderDate,25)
FROM Calender
OPTION (MAXRECURSION 0)
我正在使用sql-server 2014。
答案 0 :(得分:1)
我们不是来为你做功课,也不是为了完成作业的目的。
那说,一些提示让你去 -
答案 1 :(得分:0)
尝试这样的事情......
Declare @Date DATE = '20151104';
WITH X AS
(
SELECT TOP (31)
YEAR(@Date) AS [Year]
,MONTH(@Date) AS [Month]
,RIGHT('00' + CAST(ROW_NUMBER()
OVER (ORDER BY (SELECT NULL)) AS VARCHAR(2)),2) [Days]
FROM master..spt_values
), Dates AS
(
SELECT TRY_CONVERT ( DATE, ( CAST( [Year] AS varchar(4))
+ CAST( [Month] AS varchar(2))
+ CAST( [Days] AS varchar(2))) ) DatesVals
FROM X
)
Select * FROM Dates
Where DatesVals IS NOT NULL
答案 2 :(得分:0)
此功能将创建一个月内所有日期减去格式的列表。你应该能够自己添加它:
功能:
CREATE FUNCTION f_get_months_dates
(
@mydate DATETIME
)
RETURNS TABLE
AS
RETURN
WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
SELECT top (day(EOMonth(@mydate)))
dateadd(d, N, EOMonth(@mydate, -1)) CalendarDate
FROM tally
ORDER BY N
如何使用功能的示例:
SELECT CalendarDate
FROM f_get_months_dates(getdate())
结果:
当月的所有日期
答案 3 :(得分:-1)
您可以尝试DateAdd
功能来获取所有日期。以下是如何执行此操作的示例:
Create FUNCTION dbo.DatesBetween(@mydate date)
RETURNS @dates TABLE (
DateValue date NOT NULL
)
AS
BEGIN
declare @startDate Date= dbo.firstday(@mydate);
declare @endDate Date=dbo.lastday(@mydate);
WHILE (@startDate <= @endDate) BEGIN
INSERT INTO @dates VALUES (@startDate);
SET @startDate = DATEADD(day, 1, @startDate);
END;
RETURN;
END;
select * from dbo.DatesBetween(GETDATE()) ;