0

I have built a select statement to pick the date the participant was first recorded in the database. However I want to create a function out of this select statement to use it. I am fairly new to SQL and have never built a function before. My select statement looks like this:

Select DATEDIFF(day, (select min(startdatetime)
                        from GamePlay
                     ), enddatetime)
  from GamePlay
 where ParticipantID = '200'

My attempted function looks like this:

CREATE FUNCTION daysPlayed (@ParticipantID int)
RETURNS DateTime
AS
BEGIN
    Return DATEDIFF(day, (select min(startdatetime)
                            from GamePlay
                         ), enddatetime)
      from GamePlay
     where ParticipantID = @ParticipantID
END
GO
2
  • Sounds like you'd want a stored procedure instead. Commented Sep 25, 2012 at 16:16
  • I want to call the function in a view to create a column though? Commented Sep 25, 2012 at 16:22

2 Answers 2

3

DATEDIFF does not return a datetime. It returns an int.

Your function might look like this:

CREATE FUNCTION daysPlayed (@ParticipantID int)
RETURNS INT
AS
BEGIN
    DECLARE @result INT
    SELECT @result=DATEDIFF(day, (select min(startdatetime) from GamePlay), enddatetime) from GamePlay where ParticipantID = @ParticipantID
    RETURN @result

END

but i don't think it will do what you want it to do. Also, please note that using functions in selects over a large number of rows is a guarantee performance hit and you might not be able to use some of the indexes you set up in your tables.

Sign up to request clarification or add additional context in comments.

Comments

1

I don't know exactly what you want but see this sample might be helpful

CREATE FUNCTION mDay (@Date nchar(10))
RETURNS nchar(2)
AS
BEGIN
RETURN substring(@Date,9,2)
END


SELECT     dbo.Courses.MID, dbo.Masters.ID, dbo.Masters.Name,COUNT(CASE dbo.mDay(CDate) WHEN '01' THEN 2 END) AS day1

FROM         dbo.Courses INNER JOIN
                  dbo.Masters ON dbo.Courses.MID = dbo.Masters.MCode
WHERE     (dbo.Courses.CLevel = @Kind) AND (dbo.Courses.CDate BETWEEN @Date1 AND @Date2)
GROUP BY dbo.Courses.MID, dbo.Masters.Name, dbo.Masters.Family, dbo.Masters.ID

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.