Original SQL table-valued Function: Returns the number of custom weeks from the beginning of the current week

Source: Internet
Author: User

As always, a short blog post records a problem encountered during the development process. The original intention is to record some of their own idea, but also want to be able to help some coincidence encounter such a problem, the need for the beginning is because, to count the last n weeks of sales data.

Let's take a look at the effect of the execution function, such as SELECT * FROM [dbo]. [Fn_runweek] (-12)

The specific functions are as follows:

-- =============================================
-Call: SELECT * FROM [dbo]. [Fn_runweek] (-12)
--Create date:2015-01-14
--Description: Returns the N-week data from the beginning of the week (52 weeks a year)
-- =============================================
ALTER FUNCTION [dbo]. [Fn_runweek] (@num int=-12)
RETURNS @tab TABLE
(
Sale_year VARCHAR (10),
Xsdate VARCHAR (10),
Sort INT
)
As
BEGIN
DECLARE @week INT
SELECT @week =datepart (wk, GETDATE ())
DECLARE @i INT
SET @i=0
while (@i> @num)
BEGIN
INSERT into @tab
SELECT [Sale_year] = year (DATEADD (week, @i, GETDATE ())),
[Xsdate] = DATEPART (wk, (DATEADD (week, @i, GETDATE ())),
Sort = @i
SET @[email protected]
END
RETURN
END

if friends think that may be used later, welcome reprint, of course, can also recommend, thank you.

PS: This blog post is written using Windows Live Writer 2012, and the format effect may not be good.

Original SQL table-valued Function: Returns the number of custom weeks from the beginning of the current week

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.