Monday, October 13, 2008

T-SQL - If the Day is week day OR week end

Many Application needs this so trying to post this.

( I am not the author of this bu thought to help all by posting it here)

create function fn_IsWeekDay
(
@date datetime
)
returns bit
as
begin
declare @dtfirst int
declare @dtweek int
declare @iswkday bit
set @dtfirst = @@datefirst - 1
set @dtweek = datepart(weekday, @date) - 1
if (@dtfirst + @dtweek) % 7 not in (5, 6)
set @iswkday = 1 --business day
else
set @iswkday = 0 --weekend
return @iswkday
end


Short and sweet.

Now you can simply do this: (USAGE)


if dbo.fn_IsWeekDay(@date) = 1
begin
--do some magic here ;-)
end
--or
select a.SomeFieldsForCalculation from table a where dbo.fn_IsWeekDay(a.SomeDateField) = 1



and all is good.

No comments: