2014-10-30 34 views
0

下午好第N个号码平日,在WHERE子句中使用函数返回月份

我打开了该功能,让我每月的第N号工作日,但挣扎在使用它我的WHERE子句来过滤掉在适用于此功能的日期上。功能代码是这样的:

CREATE FUNCTION [dbo].[fnGetNthWeekdayOfMonth] 
(
    @theDate DATETIME, 
    @theWeekday TINYINT, 
    @theNth SMALLINT 
) 
RETURNS DATETIME 
BEGIN 
    RETURN (
       SELECT theDate 
       FROM (
          SELECT DATEADD(DAY, 7 * @theNth - 7 * SIGN(SIGN(@theNth) + 1) +(@theWeekday + 6 - DATEDIFF(DAY, '17530101', DATEADD(MONTH, DATEDIFF(MONTH, @theNth, @theDate), '19000101')) % 7) % 7, DATEADD(MONTH, DATEDIFF(MONTH, @theNth, @theDate), '19000101')) AS theDate 
          WHERE @theWeekday BETWEEN 1 AND 7 
            AND @theNth IN (-5, -4, -3, -2, -1, 1, 2, 3, 4, 5) 
         ) AS d 
       WHERE DATEDIFF(MONTH, theDate, @theDate) = 0 
      ) 
END 

所以我想在我的WHERE子句中使用如上所述的函数。 我怎么做这是目前我得到的:

An expression of non-boolean type specified in a context where a condition is expected, near ')'. 

它工作正常,在日期字段格兰SELECT语句时。

在此先感谢。

+1

你在哪里使用此功能 – Dbloch 2014-10-30 15:18:53

+8

噢,我的,请建立一个日历表,请添加您的查询。 – 2014-10-30 15:36:52

+1

日历桌将改变你的生活! – Zane 2014-10-30 15:55:04

回答

0

您可以使用您的功能,如下所示。

假设你有一个表有日期列d,你想找到为止d这是4日星期日十月。 (这假设这周从星期一开始)。

select d from t 
where d = dbo.fnGetNthWeekdayOfMonth('2014-10-01',7,4) 

如果你想测试它,没有和日期列相应的表,你可以使用下面的示例代码进行测试。

;with Dates (my_date) as (
    select DATEADD(day,number,'2014-10-01') 
    from master..spt_values where number < 31 and type='p' 
) 
select * from Dates 
where my_date = dbo.fnGetNthWeekdayOfMonth('2014-10-01',7,4) 

结果:

my_date 
2014-10-26 00:00:00.000 
+1

谢谢jpw。我必须有一个这样的日子......需要从我的屏幕argghhhh中断 – 2014-10-30 16:14:47

相关问题