views:

83

answers:

2

Hi Folks,

I'm trying to generate some sql that is used to calculate some final scores -> think kids at school and their end of year scores.

I was going to have about 5 or so Scalar UDF's that, accept some simple values (eg. current score, subjectid, whatever) and then spit out a decimal value.

eg.

CREATE FUNCTION [dbo].[GetRatingModifier]
(
    @ExamScore DECIMAL(6, 2),
    @Project1Score DECIMAL(6, 2),
    @Project1Score DECIMAL(6, 2),
    @Project1Score DECIMAL(6, 2),
    @SubjectTypeId TINYINT
)
RETURNS DECIMAL(8,5)
AS
BEGIN
    DECLARE @Score DECIMAL(8,5)

    SELECT @Score = (CASE @Project1Score
                     WHEN 1 THEN 10
                     WHEN 2 THEN 12.4
                      ....) +
                    (CASE blah.. u get the drift)..
    RETURN @Score
END

The logic has only maths. No select xxx from table yyy etc..

So, is this ok to do with regards to performance?

+3  A: 

Sure, no problem - performance will be almost the same as if when you would do it inline at every SELECT. I don't think this should be any problem at all - quite the contrary, putting this into an UDF seems like a really good idea! (to keep your T-SQL code clean and simple).

Marc

marc_s
So udf's should be cautiously considered in the select clause, if the udf itself, is doing some select blah from table foo, etc.. ?? (i've been reading some stuff today about udf's aren't very good to use re: performance .. and even trying to use TVF's instead..) ?
Pure.Krome
UDF's are okay - just don't overuse them. I like them for putting a bunch of CASE..... together into one place - don't splatter your code with needless repetition.
marc_s
And a UDF can be a good choice for things like lookups and so forth - just be aware of what they're doing! Use them with care - and you'll be fine!
marc_s
If you use UDF's in the WHERE clause of your query, they can sometimes hide the fact that there's code in there that will cause the SQL query optimizer to forgo any indices - that's where they can be deceptive and cause massive performance problems.
marc_s
thanks marc :) most appreciated :)
Pure.Krome
A: 

Yes, it's a bad idea because you should put all your score weights in a table and perform a join to get the result.

erikkallen