SQLUSA

Microsoft SQL Server 2008
Database Design Best Practices

How to find the first work day of a month?

 

Execute the following script in Query Editor to create a user-defined function (UDF) to calculate the first work day in a month:


use AdventureWorks2008;

go

create function fnFirstWorkDayOfMonth( @Year int, @Month int)

returns datetime

as

begin

declare @FirstDayOfMonth datetime

set @FirstDayOfMonth = convert(datetime, convert(varchar,@Year)+'-'+convert(varchar,@month)+'-01')

if datepart(weekday,@FirstDayOfMonth) not in (1,7)

      return (@FirstDayOfMonth)

set @FirstDayOfMonth = dateadd(day,1,@FirstDayOfMonth)

if datepart(weekday,@FirstDayOfMonth) not in (1,7)

      return (@FirstDayOfMonth)

      return (dateadd(day,1,@FirstDayOfMonth))

end

go

 

select dbo.fnFirstWorkDayofMonth (

      year(getdate()),

      month(getdate())

      )

go

 

 

The Best SQL Server 2008 Training in the World
 
 
SQLUSA.com Home Page