use test;
GO
/*创建自定义函数的格式:
* create function 函数名(参数 数据类型)
* returns 返回数据类型 as
* begin
* 代码
* end
*/ --创建一个自定义函数,计算两个整数的和
create function Addition(@num1 int , @num2 int)
returns int as
begin
declare @result int;
set @result = @num1 + @num2;
return @result;
end
GO
select [dbo].Addition(200,100)
--使用print调用
print [dbo].Addition(200,100)
--使用exec调用函数(参数不用括号)
declare @myresult int;
exec @myresult = [dbo].Addition 200,100
--使用drop删除Addition函数
drop function [dbo].Addition
练习(完整)
--创建表
create table Class130(
id int primary key identity,
stuName varchar(12),
stuAge int,
stuSex nchar(1) default ('男'),
Brithday datetime default(getdate()),
teacherName varchar(12) defualt ('Young Sir')
) --插入数据
insert into Class130(StuName) values ('Viusuangio') --函数查询表数据(传参)
create function getTeacherName(@stuname varchar(12))
returns table as
return(
select stuName , teacherName from Class130
where stuName = @stuname
)
GO
select * from [dbo].getTeacherName('Viusuangio'); --创建函数,传入整数,与1024比较;
create function judgeWith1024(@num int)
returns varchar(20) as
begin
declare @output varchar(20);
if @num > 1024
set @output = '判断:'+@num+'大于1024';
if @num = 1024
set @output = '判断:'+@num+'等于1024';
else
set @output = '判断:'+@num+'小于1024';
return @output;
end
GO /*根据学号判断学生的出生日期是否是闰年
* 1.普通年能被4整除且不能被100整除的为闰年.
* 2.世纪年能被400整除的是闰年
*/ create function judgeLeapYear(@stuno varchar(12))
returns varchar(20) as
begin
declare @year int , @output varchar(20);
set @year = (select year(Brithday) from StuInfo where stuNo = @stuno);
if @year%4 = 0 and @year%100<>0
set @output = '该学生出生年是闰年';
else
set @output = '该学生出生年非闰年';
return @output;
end
GO --计算1+2+3+……+100的和,并用print显示计算结果
create function additionFrom1To100()
returns int as
begin
declare @result int , @addnum int;
set @result = 0;
set @addnum = 1;
while @num <= 100 begin
set @result += @addnum;
set @addnum += 1;
end
return @result;
end
GO
print [dbo].additionFrom1To100()