简体   繁体   English

SQL中的用户定义的标量函数

[英]User Defined Scalar functions in SQL

I am new to SQL and am learning User Defined Functions in SQL 我是SQL新手,正在学习SQL中的用户定义函数

I have two tables and I have given the rows I have inserted to those tables. 我有两个表,并给出了插入这些表的行。

--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)

I require a help about creating Scalar functions and I need to get 我需要有关创建标量函数的帮助,我需要获取

  1. A scalar function which will return the Student ID of the student who got highest mark in 'Maths' 标量函数将返回在“数学”中得分最高的学生的学生ID
  2. A tabular function which will return the student ID and marks gained by the student who got highest total mark. 表格函数,将返回学生ID和由得分最高的学生获得的分数。

Am just trying to learn SQL. 我只是想学习SQL。 I have tried - " 我努力了 - ”

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)

for the first one. 对于第一个。 It does not look good. 看起来不太好。

It looks like this what you want for 1. 看起来像这样您想要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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM