Reputation: 19
i have a database called tblsignup and a table called registration. in registration table it has colum of Id, name lastname, age, and gender. I want to identify if the first row is a male or female
is my query correct? sorry I'm noob.
create function MorF (@stats int)
returns int
as
begin
declare @stats = int
set @stats = 0
declare @gender nvarchar(50)
set @gender = (select Gender from registration where id = 0x)
if @gender = 'Male'
begin
set @stats = 1
end
else
begin
set @stats = 0
end
returns @stats
end
Upvotes: 0
Views: 392
Reputation: 1270311
This looks like SQL Server. If so, I would recommend a single statement scalar function. This simply looks like:
create function MorF (@id int)
returns int
as
begin
return (select (case when gender = 'Male' then 1 else 0 end)
from registration r
where r.id = @id
);
end;
Here is a db<>fiddle.
One of the major changes is in the WHERE
clause of the subquery. This assumes that the parameter being passed in is the id
of interest. I renamed the parameter to @id
for clarity.
Also note that your local parameter @stats
conflicts with the parameter being passed in. The above code just side-steps that problem by avoiding internal parameters.
Upvotes: 1