0

Non-database programmer here. It happens so, that I need to create a function in T-SQL which returns workdays count between given dates. I believe that the easiest how it's done is with while loop. Problem is, that as soon as I write something like

while @date < @endDate
begin

end

the statement won't execute, claiming "incorrect syntax near the keyword 'return'" (not very helpful). Where's the problem?

P.S. Full code:

ALTER FUNCTION [dbo].[GetNormalWorkdaysCount] (
@startDate DATETIME,
@endDate DATETIME
)   
RETURNS INT

AS
BEGIN
    declare @Count INT,
            @CurrDate DATETIME
    set @CurrDate = @startDate

    while (@CurrDate < @endDate)
    begin

    end

    return @Count
END
GO
2
  • 1
    Code snippet with function declaration and all the return statements would be helpful, to interpret the error message. Commented Oct 8, 2012 at 6:59
  • please show some more code so that we can help.. Commented Oct 8, 2012 at 6:59

2 Answers 2

5

Unlike some languages, the BEGIN/END pair in SQL Server cannot be empty - they must contain at least one statement.


As to your actual problem - you've said you're not a DB programmer. Most beginners to SQL tend to go down the same route - trying to write procedural code to solve the problem.

Whereas, SQL is a set-based language - it's usually better to find a set-based solution, rather than using loops.

In this instance, a calendar table would be a real help. Such a table contains one row for each date, and additional columns indicating useful information for your business (e.g. what you consider to be a working day). It then makes your query for working days look like:

SELECT COUNT(*) from Calendar
where BaseDate >= @StartDate and BaseDate < @EndDate and IsWorkingDay = 1

Populating the Calendar table becomes a one off exercise, and you can populate it with e.g. 30 years worth of dates easily.

Sign up to request clarification or add additional context in comments.

Comments

3

Using any loop within SQL server is never a good idea :)

There are few better solutions, referring to one presented on StackOverflow already.

2 Comments

using loop is never a good idea ? Never is a long time. I can give you several examples where looping is good. Normally i avoid looping, but in this example i think it is the best answer: stackoverflow.com/questions/12776195/…
Ok, let me re-state this - It's not a good idea to start thinking about looping before trying other options. Example your're referring to is simply soluble without looping, see my answer in there ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.