經典SQL自訂函數

來源:互聯網
上載者:User

1、確定某年某月有多少天

實現原理:先利用DATEDIFF取得當前月的第一天,再將月份加一取得下月第一天,然後減去1分鐘,再取日期的

                   天數部分,即為當月最大日期,也即當月天數

CREATE FUNCTION DaysInMonth ( @date datetime ) Returns int
AS
BEGIN
 RETURN Day(dateadd(mi,-3,DATEADD(m, DATEDIFF(m,0,@date)+1,0)))
END

調用樣本:

select dbo.DaysInMonth ('2006-02-03') 

 

(2)計算哪一天是本周的星期一

SELECT DATEADD(week, DATEDIFF(week,'1900-01-01',getdate()), '1900-01-01')  --返回2006-11-06 00:00:00.000
或
SELECT DATEADD(week, DATEDIFF(week,0,getdate()),0)     

(3)當前季度的第一天

SELECT DATEADD(quarter, DATEDIFF(quarter,0,getdate()), 0)—返回2006-10-01 00:00:00.000

(4)一個季度多少天

declare @m tinyint,@time smalldatetime

select @m=month(getdate())
select @m=case when @m between 1 and 3 then 1
                       when @m between 4 and 6 then 4
                       when @m between 7  and 9 then 7
                       else 10 end

select @time=datename(year,getdate())+'-'+convert(varchar(10),@m)+'-01'
select datediff(day,@time,dateadd(mm,3,@time)) —返回92

5)字串轉為資料類型(real,實數),自動截取數字轉換

Alter FUNCTION ToNumeric (@str varchar(20)) RETURNS real
AS
BEGIN
 declare @temp char(1);
 declare @num varchar(20);
 declare @dot bit;
 declare @i int;
 declare @length int;

 set @num = '';
 set @dot = 0;
 set @i = 1;
 set @length = len(@str);
 
 set @temp = substring(@str,@i,1);

 while (isnumeric(@temp) = 1)
 begin
  set @num = @num + @temp;
  set @i = @i +1;
  set @temp = substring(@str,@i,1);
  
  if ('.' = @temp)
  begin
   if (1 = @dot)
    break;
   else
    set @dot = 1;
  end

 end

 return cast(@num as real);
END

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.