Classic SQL Custom Functions

Source: Internet
Author: User

1. Determine how many days a certain year

Implementation principle: First use DateDiff to obtain the first day of the current month, and then add a month to get the first day of next month, then subtract 1 minutes, then take the date

Number of days, that is, the maximum date of the month, or the number of days of the month

CREATE FUNCTION daysinmonth (@date datetime) Returns int

As

BEGIN

Return Day (DateAdd (Mi,-3,dateadd (M, DATEDIFF (m,0, @date) +1,0))

End

Call Example:

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

(2) Calculate which day is Monday of the week

SELECT DATEADD (Week, DATEDIFF (week, ' 1900-01-01 ', GETDATE ()), ' 1900-01-01 ')--return to 2006-11-06 00:00:00.000

Or

SELECT DATEADD (Week, DATEDIFF (Week,0,getdate ()), 0)

(3) The first day of the current quarter

SELECT DATEADD (Quarter, DATEDIFF (Quarter,0,getdate ()), 0)-back to 2006-10-01 00:00:00.000

(4) How many days a quarter

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 Ten End

Select @time =datename (year,getdate ()) + '-' +convert (varchar (), @m) + '-01 '

Select DateDiff (Day, @time, DateAdd (mm,3, @time))-return 92

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.