Sql Server选择案例日期

时间:2014-06-06 12:02:48

标签: sql-server sql-server-2012 case

我正在尝试创建一个需要两个日期的存储过程(reportStartDate,reportEndDate)。

我们的想法是返回所有内容(" startDate"," endDate"" term"是重要的列),包括&#之间的工作天数34; reportStartDate"和" reportEndDate"但是" startDate"和" endDate"可能落在" reportStartDate"和" reportEndDate"所以我需要检查是否发生这种情况并使用这些日期来计算出这些日子。 (如果"术语" = 1然后使用" endDate"否则使用" reportEndDate")

我使用此代码来获取工作日

(DATEDIFF(dd,startDate,endDate) - (2* DATEDIFF(wk,startDate,endDate)))+1 AS BusinessDayCount

这对于显然无法正常工作的存储过程

Create  PROCEDURE testPro(    
@reportStartDate date,
@reportEndDate date    
)    
AS
BEGIN    
SELECT emp, surname, startDate, endDate, 
CASE WHEN startDate<= @reportStartDate 
THEN (DATEDIFF(dd,@reportStartDate, @reportEndDate) - (2* DATEDIFF(wk,@reportStartDate,@reportEndDate)))+1 AS BusinessDayCount 
ELSE (DATEDIFF(dd,startDate, @reportEndDate) - (2* DATEDIFF(wk,startDate,@reportEndDate)))+1 AS BusinessDayCount END 
FROM Table_1
END
EXEC  testPro '2012-01-01', '2012-12-31'

任何人都可以帮助或指出我正确的方向。感谢

2 个答案:

答案 0 :(得分:0)

除了案例陈述之外,我没有看到您的程序有任何问题。应该如下

CASE WHEN startDate<= @reportStartDate 
THEN (DATEDIFF(dd,@reportStartDate, @reportEndDate) - (2* 
DATEDIFF(wk,@reportStartDate,@reportEndDate)))+1  
ELSE (DATEDIFF(dd,startDate, @reportEndDate) - (2* 
DATEDIFF(wk,startDate,@reportEndDate)))+1 END AS BusinessDayCount

语法是:

case when (condition) then some_value 
else some_other_value end as some_alias_name

答案 1 :(得分:0)

以下内容在SQL Server中可以正常工作:

CREATE PROCEDURE testPro @reportStartDate date, @reportEndDate date
AS
SELECT emp, surname, startDate, endDate, (DATEDIFF(dd, @reportStartDate, @reportEndDate) + 1) -(DATEDIFF(wk, @reportStartDate, @reportEndDate) * 2) -(CASE WHEN DATENAME(dw, @reportStartDate) = 'Sunday' THEN 1 ELSE 0 END) -(CASE WHEN DATENAME(dw, @reportEndDate) = 'Saturday' THEN 1 ELSE 0 END) AS BusinessDayCount FROM Table_1 GO

我已经用另一个稍微更准确的计算(假设您的工作日从星期一到星期五开始)替换了您对BusinessDayCount的计算,如果没有,那么您只需用以下代码替换该位代码: / p>

CASE WHEN startDate<= @reportStartDate 
THEN (DATEDIFF(dd,@reportStartDate, @reportEndDate) - (2* 
DATEDIFF(wk,@reportStartDate,@reportEndDate)))+1  
ELSE (DATEDIFF(dd,startDate, @reportEndDate) - (2* 
DATEDIFF(wk,startDate,@reportEndDate)))+1 END AS BusinessDayCount