SQL Function to Determine Day Type (Work Day vs. Week Day)
January 25th, 2012 / No Comments » / by admin
Here is a little handy function which I use to either determine day type in some ad hoc query or populate date dimension in the data warehouse via SQL Server Integration Services (on that see the upcoming posts). All I do is pass the date parameter (in a “datetime” data type) to determine if the date is classed as a work day or weekend. It’s a really neat and simple solution as you don’t have to construct the code to determine the field value as part of the larger query; all it takes is just a simple function call. The code behind the solution as well as an execution sample is below:
--------------------------------------------------------------------------------------
-- CREATE A SCALAR-VALUED FUNCTION TO DETERMINE DAY TYPE CODE
--------------------------------------------------------------------------------------
CREATE FUNCTION [dbo].[Day_Type_Code]
(@Date datetime)
RETURNS varchar (10)
AS
BEGIN
DECLARE @dtfirst int
DECLARE @dtweek int
DECLARE @iswkday varchar(10)
SET @dtfirst = @@datefirst - 1
SET @dtweek = DATEPART(weekday,@date)-1
IF(@dtfirst + @dtweek)%7 not in (5,6)
SET @iswkday = 'WD'
ELSE
SET @iswkday = 'WE'
RETURN @iswkday
END
GO




Great post Martin and I found that the source code worked well. My company was about procure and deploy an…