Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 User Defined Function problems

Author  Topic 

likwid
Starting Member

3 Posts

Posted - 2001-11-11 : 17:39:58
I am trying to make a poll.

Current Tables

Polls
===============
id int
pollText varChar(255)
StartDate datetime
EndDate datetime

PollOptions
================
id int
pollID int
OptionText varChar(150)
Votes int

I have a UDF named dbo.udf_ReturnPollResults (Code Below) then takes the number of options and divides them by the total number of votes. I then cast these values as float to get a percentage value. The percentage value is what I am returning.

/** Function to return percentage value **/
CREATE FUNCTION udf_ReturnPollResult
(@PollID int,
@PollOptionID int)
RETURNS float
AS
BEGIN
DECLARE @TotalVotes int
DECLARE @OptionTotal int
DECLARE @constPercent real
DECLARE @Result float

SELECT @TotalVotes = SUM(Votes) FROM pollOptions WHERE pollID = @pollID
SELECT @OptionTotal = Votes FROM pollOptions WHERE [id] = @pollOptionID
SELECT @Result = Cast(@OptionTotal as float) / Cast(@TotalVotes as float)
RETURN (@Result)
END

I have a stored procedure usp_GetPolLResults (Code Below) which does a simple select and calls the function to select the result into the recordset.

CREATE PROCEDURE dbo.usp_GetPollResults
(@pollID int)
AS
SELECT [id],[pollID],dbo.udf_ReturnPollResult(@pollID,[id]) AS Result FROM pollOptions


I have 3 records in the PollOptions table

[ID] [PollID] [OptionText] [Votes]
1 1 Yes 16
2 1 No 14
3 1 Don't Care 3


When I Execute my stored proc usp_GetPollResults i get the following result ...

[ID] [PollID] [Results]
1 1 0.48484848484848486
2 1 0.42424242424242425
3 1 9.0909090909090912E-2

Obviously the 3rd value is incorrect

however when I do

PRINT dbo.udf_ReturnPollResult(1,3)

I get the correct value for for the third row (0.0909091)

Any ideas?


./Likwid
   

- Advertisement -