简体   繁体   English

在T-SQL函数中使用while循环

[英]Using while loop in T-SQL function

Non-database programmer here. 这里是非数据库程序员。 It happens so, that I need to create a function in T-SQL which returns workdays count between given dates. 碰巧是这样,我需要在T-SQL中创建一个函数,该函数返回给定日期之间的工作日计数。 I believe that the easiest how it's done is with while loop. 我认为最简单的方法是使用while循环。 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). 该语句将不会执行,声称“关键字'return'附近的语法不正确”(不是很有帮助)。 Where's the problem? 哪里出问题了?

PS Full code: PS完整代码:

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

Unlike some languages, the BEGIN / END pair in SQL Server cannot be empty - they must contain at least one statement. 与某些语言不同,SQL Server中的BEGIN / END对不能为空-它们必须至少包含一个语句。


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. 大多数SQL初学者倾向于走同一条路-尝试编写过程代码来解决问题。

Whereas, SQL is a set-based language - it's usually better to find a set-based solution, rather than using loops. 鉴于SQL是一种基于集合的语言-通常最好找到一个基于集合的解决方案,而不是使用循环。

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 (eg 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 eg 30 years worth of dates easily. 填写“日历”表成为一项一次性的练习,您可以轻松地为其填充例如30年的日期。

Using any loop within SQL server is never a good idea :) 在SQL Server中使用任何循环绝不是一个好主意:)

There are few better solutions, referring to one presented on StackOverflow already . 几乎没有更好的解决方案,请参考已经在StackOverflow上提出的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM