SQL Server calculates the number of weeks and the number of weeks based on the Start week.

Source: Internet
Author: User

Because SQL server does not calculate the number of weeks and the number of weeks based on the Start Week (Monday is the first day of a week or Sunday, share with you.

I. Calculate the number of weeks based on the Start week: fn_getweekday

Create Function [DBO]. [fn_getweekday] (@ inputdate date, -- @ firstdayofweek value: 1 to 7. If it is 1, Monday indicates the first day of a week. If it is 7, Sunday indicates the first day of a week. @ Firstdayofweek Int = 1) returns intasbegin return datepart (DW, dateadd (D, @ datefirst-@ firstdayofweek, @ inputdate) End

Ii. Calculate the number of weeks based on the Start week: fn_getweeknumber

Create Function [DBO]. [fn_getweeknumber] (@ inputdate date, -- @ firstdayofweek) the value ranges from 1 to 7. If it is 1, Monday indicates the first day of a week. If it is 7, Sunday indicates the first day of a week. @ Firstdayofweek Int = 1) returns intasbegin declare @ weekdayofnewyearday int set @ weekdayofnewyearday = [DBO]. fn_getweekday (datename (year, @ inputdate) + '-01-01', @ firstdayofweek) return ceiling (datepart (dy, @ inputdate)-(@ firstdayofweek-@ response + 1 )) /7) + 1end

Note: The above functions are not affected by the cultural settings and @ datefirst global variables. In any case, the correct results can be returned.

Related Article

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.