选择日期和计数变量

时间:2014-03-06 15:18:55

标签: sql date select count

我已经制作了一个存储过程,我需要它来检查日期范围内的每个日期。日期从浏览器(我的表单)传递,然后在存储过程中设置为变量。

当它在日期范围之间进行检查时我还需要它来计算其他东西,例如我有一个@max_users常量,如果所选日期之间的日期有20个人,则将变量设置为false。

这是迄今为止在日期范围之间进行选择的代码。

    SELECT (SOME FORM OF COUNTER TO COUNT VARIABLES WOUDL GO HERE)
    FROM table 
    WHERE @Startdate => @StartDate AND =< @EndDate

我是SQL新手,遇到麻烦。

    CREATE PROCEDURE spBusinessRules (@Startdate date, @Enddate date, @EmployeeID int)

/*****
Name:spBusinessRules
Description: Checks the holiday agaisnt all the business rules ready for accepting or declining
*****/
AS
    BEGIN
        SELECT COUNT(*)
        FROM Holidays
        WHERE @Startdate >= @Startdate AND @Enddate <= @Enddate AND (SELECT jobrole FROM Employees WHERE ID = @EmployeeID) = JobRole
    END

    SELECT * FROM Employees

以上是我的最新尝试,我仍然遇到问题

2 个答案:

答案 0 :(得分:0)

最好的方法是在SQL中声明一个获取参数(Date)的函数。然后,您可以在函数中进行计算,并将值返回到此语句以显示。

答案 1 :(得分:0)

最后,我设法做到这一点是工作成果

DECLARE @EmployeeID int
DECLARE @StartDate date
DECLARE @EndDate date
DECLARE @JobRoleID int

SET @JobRoleID = 2
SET @EmployeeID = 2010
SET @Startdate = '2013-03-13'
SET @EndDate = '2015-03-14'

/*Sets The max days off for the users jobrole*/
DECLARE @EmployeeJobroleMAX int
SET @EmployeeJobroleMAX = (SELECT maxusersOffPerDay 
                           FROM JobRole 
                           WHERE @JobRoleID = JobRole.ID)
DECLARE @JobRoleOff int

BEGIN
    DECLARE @DateCount date
    SET @DateCount = @Startdate

    DECLARE @EndDateCheck date
    SET @EndDateCheck = DATEADD(d, 1, @EndDate)

    WHILE(@DateCount <> @EndDateCheck)
        BEGIN

            SET @JobRoleOff = (SELECT COUNT(*) JobRoleID 
                               FROM Employees 
                               RIGHT JOIN Holidays 
                                       ON Employees.ID = Holidays.EmployeeID 
                               WHERE @EmployeeID = Employees.ID 
                                     AND Holidays.StartDate >= @StartDate 
                                     AND Holidays.EndDate <= @EndDate)
            SET @DateCount = DATEADD(d, 1, @DateCount)
        END

    IF(@JobRoleOff >= 1)
        BEGIN
            SELECT @JobRoleOff AS Failed
        END
END