Showing posts with label Function. Show all posts
Showing posts with label Function. Show all posts

Weekday(s) statistics in a Month and Year

To findout count statistics for each weekdays in a particular Year and Month

--Creating a Stored Procedure
If OBJECT_ID('USP_Weekdays') Is Not Null
Drop Proc USP_Weekdays
Go
Create Proc USP_Weekdays
(
@Year Int,
@Month Varchar(15)
) As
Begin
Set Nocount on
 Declare @Days TinyInt
Select @Days = Dbo.HowManyDays(@Year,@Month)

;With WeekDays
As
(
Select 1 [Days]
Union All
Select [Days] + 1 from WeekDays where [Days] <31
)

Select SUM([Sunday]) [Sunday], SUM([Monday]) [Monday], Sum([Tuesday]) [Tuesday], Sum([Wednesday]) [Wednesday], SUM([Thursday]) [Thursday], Sum([Friday]) [Friday], SUM([Saturday]) [Saturday]
From
(
Select Case [Day] When 'Sunday' Then 1 Else 0 End [Sunday],
Case [Day] When 'Monday' Then 1 Else 0 End [Monday],
Case [Day] When 'Tuesday' Then 1 Else 0 End [Tuesday],
Case [Day] When 'Wednesday' Then 1 Else 0 End [Wednesday],
Case [Day] When 'Thursday' Then 1 Else 0 End [Thursday],
Case [Day] When 'Friday' Then 1 Else 0 End [Friday],
Case [Day] When 'Saturday' Then 1 Else 0 End [Saturday]
from
(
select DATENAME(weekday,Cast(@Year as Varchar) + '-' + @Month + '-' + Cast([Days] as varchar)) [Day] from WeekDays Where [Days] <= @Days
) as X
) as WeekDays
End
Go

--Executing the Stored Procedure
Exec USP_Weekdays 2011,'June'
Go

Note: You can find the dbo.HowManyDays function script from the following post
http://sqlserverbuddy.blogspot.com/2011/06/how-many-days-in-month.html

--Result

How many days in a month ?

To findout how man days in a particular month

If Object_Id('Dbo.HowManyDays') Is Not Null
Drop Function Dbo.HowManyDays
Go
Exec(
'Create Function Dbo.HowManyDays(@Year Int,@Month Varchar(15)) Returns Int
As
Begin
Declare @Date Varchar(50),
@Days TinyInt
 Select @Date = Cast(@Year as Varchar) + ''-'' + @Month + ''-01'',
@Days = DatePart(Day,DateAdd(Month,1,@Date) -1)
 Return @Days
End')

--How to Execute it
Select Dbo.HowManyDays(2011, 'June') [Days]
Go


Cannot find either column "dbo" or the user-defined function or aggregate "Function Name", or the name is ambiguous.


The functions is not there in current database.

Here I have created one stored procedure and Inside the procedure, I use one function named "UFN_Test1", But actually the function is not there in current database.

Try to re-produce the Err:
IF OBJECT_ID('USP_Test1','P') IS NOT NULL
DROP PROC USP_Test1
GO
CREATE PROC USP_Test1
AS
BEGIN
SELECT dbo.UFN_Test1()
END
GO


Execute the procedure
EXEC USP_Test1
GO


When executing the procedure, The following Err occurred...

Cannot find either column "dbo" or the user-defined function or aggregate "Function Name", or the name is ambiguous.

How to identify whether the function is there in current database or not ?

IF OBJECT_ID('UFN_Test1') IS NULL
PRINT 'The Object is not there...!'
ELSE
PRINT 'The Object is there...!'