创建用户自定义函数,输入月份可以返回该月的最后一天。
我的意思是创建一个存储过程,然后进行调用输出。但是又考虑到每月天数不同,不好设定函数,求解,急用,谢谢。

解决方案 »

  1.   

    declare @dt date
    set @dt='2010-05-01'
    SELECT DATEADD(Day,-1,CONVERT(char(8),DATEADD(Month,1,@dt),120)+'1')(无列名)
    2010-05-31 00:00:00.000
      

  2.   

    create proc getDate1
    @year int,
    @month int
    as
    begin
     declare @time1 datetime
     set @time1=cast((cast(@year as nvarchar)+cast((@month+1) as nvarchar)+'1') as datetime)
     select datediff(day,-1,@time1)
    end
    exec getDate1 2010,5
      

  3.   

    alter proc getDate1
    @year int,
    @month int
    as
    begin
     declare @time1 datetime
     set @time1=cast((cast(@year as nvarchar)+'-'+cast((@month+1) as nvarchar)+'-'+'1') as datetime)
     select DATEADD(day,-1,@time1)
    end
    exec getDate1 2010,5
      

  4.   

    if object_id('tb') is not null
    drop table tb
    create table tb(Mth int, Days int)
    declare @time datetime,
    @currentTime datetime,
    @month int
    --当前月第一天
    SET @currentTime = convert(varchar(8),getdate(),120) + '01 '
    SET @month = 1while @month <= 12
    BEGIN
    --由当前月第一天求出所有第month月的第一天
    SET @time = dateadd(month,-month(@currentTime)+@month + 1,@currentTime)
    insert into tb(Mth, Days) (select @month, day(DateAdd(dd,-1,@time)))
    SET @month = @month + 1
    END
    select * from tb
    drop table tb
    /*
    Mth         Days
    ----------- -----------
    1           31
    2           28
    3           31
    4           30
    5           31
    6           30
    7           31
    8           31
    9           30
    10          31
    11          30
    12          31(12 行受影响)
    */
      

  5.   

    -->SQL查询如下:--创建自定义函数模版
    IF OBJECT_ID('[fn_test]') IS NOT NULL
        DROP FUNCTION [fn_test]
    GO
    CREATE FUNCTION [fn_test](
    @dt DATETIME
    )RETURNS DATETIME
    AS
    BEGIN
    RETURN
    DATEADD(mm, DATEDIFF(mm, 0, @dt)+1, 0)-1
    END
    GOSELECT dbo.fn_test('2010-02-20') 
    /*
    -----------------------
    2010-02-28 00:00:00.000(1 行受影响)*/
    SELECT dbo.fn_test(GETDATE()) 
    /*
    -----------------------
    2010-06-30 00:00:00.000(1 行受影响)
    */
      

  6.   


    create procedure getday
    @year int,
    @month int
    as 
    begin select day(dateadd(dd, -1, dateadd(mm, 1, cast((cast(@year as varchar(100)) + '-' + cast(@month as varchar(100)) + '-1') as datetime))))end
      

  7.   


    create procedure getday
    @year int,
    @month int
    as 
    begin select day(dateadd(dd, -1, dateadd(mm, 1, cast((cast(@year as varchar(100)) + '-' + cast(@month as varchar(100)) + '-1') as datetime))))end