0

抱歉打扰各位了。我的任务是在客户端进行一些代码审查,发给我的笔记本电脑没有安装 SQL。当我在等待安装时,想忙着查看代码并遇​​到了这个 gem

CREATE FUNCTION [dbo].[Uf_GetTotalDaysInMonth]
(
    -- Add the parameters for the function here
    @anydateofMonth datetime
)
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @totalDaysInMonth int
    -- Add the T-SQL statements to compute the return value here

        DECLARE @givendate datetime
        SET @givendate = STR(Year(@givendate)) + '-' + STR(Month(@givendate) + 1) + '-01' 

        select @totalDaysInMonth = datepart(dd, dateadd(day, -1, @givendate))

    -- Return the result of the function
    RETURN @totalDaysInMonth

END

忽略不必要的额外变量的使用,我相信这个函数会在12月崩溃

STR(Month(@givendate) + 1)

将评估为 13 并将给出超出范围的日期错误。有人可以帮我验证一下吗?

4

2 回答 2

1

当通过 @anydateofMonth 十二月日期时,您将在函数中遇到错误。你可以使用这个:

CREATE FUNCTION [dbo].[Uf_GetTotalDaysInMonth]
(
    -- Add the parameters for the function here
    @anydateofMonth datetime
)
RETURNS int
AS
 BEGIN
    DECLARE @nextMonth datetime
    SET @nextMonth = dateadd(m, 1, @anydateofMonth)
    RETURN (SELECT Day(dateadd(d, -Day(@nextMonth), @nextMonth)))
  END
于 2012-11-26T09:03:04.580 回答
0

http://sqlfiddle.com/#!6/185c9/7

SQL Fiddle没有错误,只有13作为输出

于 2012-11-26T08:45:23.230 回答