I have a UDF that calculates a score based on a range of values that are going in to the table.
The UDF has to be applied/called during the table creation process, this is where I'm having a little trouble.
The UDF had to be created using case when methods only, so I can't change much on that but I'm sure I've just got something a little off.
I'm not sure if the answer is already out there or not, but I haven;t stumbled across it yet so apologies if this is something already answered.
Here is the UDF which is created first
--Create UDF
create function [dbo].[cupidscoreUDF]
(
@gender char(1),
@name varchar(15),
@dob datetime,
@weight int,
@height int,
@smoker bit,
@salary int
)
returns int
as
begin
declare @score int
-- To determine age in years
declare @Age int
select @Age = DATEDIFF(YEAR, @dob, GETDATE())
select
@score = case
when @Age between 20 and 30 then 5
when @Age between 31 and 40 then 4
when @Age between 41 and 50 then 3
when @Age > 50 then 2
else 0
end
-- To determine the height/weight ratio
declare @WeightHeight int
set @WeightHeight = @weight / @height
set
@score = @score +
case
when @WeightHeight between 20 and 25 then 1
when @WeightHeight between 25 and 30 then 3
when @WeightHeight between 30 and 35 then 4
when @WeightHeight between 35 and 40 then 2
else 0
end
-- If non-smoker add 2 points
if @smoker = 0
set @Score = @Score + 2
-- To determine score by salary
set
@score = @score +
case
when @salary < 50000 then 1
when @salary between 500001 and 60000 then 2
when @salary between 60001 and 70000 then 3
when @salary > 70000 then 4
end
return @score
end
;
Now here's what I've got for the table creation process
-- Create Member_Profile table
create table Member_Profile
(
MemberID int primary key,
Gender varchar(6),
Name varchar(50),
Dob datetime,
Weight int,
Height int,
Smoker bit,
Salary int,
Cupid as dbo.cupidscoreUDF
)
GO
insert into Member_Profile (Gender, Name, Dob, Weight, Height, Smoker, Salary) values ('Male','James',19931115, 75, 180, 0, 80000);
insert into Member_Profile (Gender, Name, Dob, Weight, Height, Smoker, Salary) values ('Female','Rosie',19870912, 45, 150, 0, 100000);
insert into Member_Profile (Gender, Name, Dob, Weight, Height, Smoker, Salary) values ('Male','Richard',19630402, 95, 168, 1, 200000);
select * from Member_Profile
The UDF takes the member's info and then calculates their 'cupid' score from that, which is then inserted along with everything else in to the table.
Any help using the UDF would be great
TRIGGERwhile inserting data to the table...