我是SQL的新手,正在学习SQL中的用户定义函数
我有两个表,并且已经将已插入的行添加到这些表中。
--Table1
create table sql_exam(
exa_examid bigint not null primary key,
exa_name varchar(100) not null,
exa_maxmark decimal(5,2) not null,
exa_minmarkreqdforpass decimal(5,2) not null,
exa_examscheduletime datetime not null
)
--Rows inserted into Table1
insert into sql_exam(exa_examid,exa_name,exa_maxmark,exa_minmarkreqdforpass,exa_examscheduletime) values (1,'Maths',100,40,'2012-10-10 10:00')
insert into sql_exam(exa_examid,exa_name,exa_maxmark,exa_minmarkreqdforpass,exa_examscheduletime) values (2,'English',75,35,'2012-10-11 10:00')
--Table2
create table sql_studentmarks(
stm_studentid int not null primary key,
stm_examid bigint foreign key references sql_exam(exa_examid),
stm_mark decimal(5,2)
)
--Rows inserted into Table2
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (1,1,80)
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (2,1,90)
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (3,1,40)
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (1,2,70)
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (2,2,60)
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (3,2,17)
我需要有关创建标量函数的帮助,我需要获取
我只是想学习SQL。我试过 - “
create function fnGetMathsHightest()
returns int
as
begin
declare @st_id int
return @st_id
end
select dbo.fnGetMathsHightest()
from sql_studentmarks
where stm_examid=1
group by stm_studentid
having stm_mark=max(stm_mark)
第一个。它看起来不太好。
答案 0 :(得分:0)
看起来这就是你想要的1。
CREATE FUNCTION ssfnGetStudenytId
(
-- Add the parameters for the function here
)
RETURNS int
AS
BEGIN
declare @vId as int
set @vId = Select stm_studentid from sql_studentmarks where stm_mark = (SELECT MAX( stm_mark )from sql_studentmarks )
RETURN @vId
END