SQL Code - Is Weekend - user defined function
I need to know - "Is this day a weekend?" This function is used to determine if a date is a Saturday or Sunday then 1 else 0.
/****** Object: UserDefinedFunction [dbo].[SA_weekend] Script Date: 05/23/2012 11:39:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[SA_weekend]
(
@Date datetime
)
RETURNS int
AS
/********************************************************************************************
Description: This function is used to determine if a date is a weekend then 1 else 0. (Saturday or Sunday)
dbo.[SA_weekend]
********************************************************************************************/
Begin
Declare @IsWeekend int
Select @IsWeekend = 0
Declare @DayofWeek varchar(10)
--SET DATEFIRST 7;
SET @DayofWeek = (SELECT
case when DATEPART(dw, @Date) = 1 then 'Sunday'
when DATEPART(dw, @Date) = 2 then 'Monday'
when DATEPART(dw, @Date) = 3 then 'Tuesday'
when DATEPART(dw, @Date) = 4 then 'Wednesday'
when DATEPART(dw, @Date) = 5 then 'Thursday'
when DATEPART(dw, @Date) = 6 then 'Friday'
when DATEPART(dw, @Date) = 7 then 'Saturday'
end)
If @DayofWeek = 'Sunday'
begin
Set @IsWeekend = 1
end
else if @DayofWeek = 'Saturday'
begin
Set @IsWeekend = 1
end
Return @IsWeekend
End
GO
To test this script -
--testing dates for weekends
declare @StartDate datetime
--set @StartDate = '5/25/2012'
--set @StartDate = '5/26/2012'
--set @StartDate = '5/27/2012'
set @StartDate = '5/27/2011'
--set @StartDate = '5/28/2011'
--set @StartDate = '5/29/2011'
select dbo.SA_weekend(@StartDate)
No comments:
Post a Comment