创建用户定义函数,它是返回值的已保存的 Transact-SQL 例程。用户定义函数不能用于执行一组修改全局数据库状态的操作。与系统函数一样,用户定义函数可以从查询中唤醒调用。也可以像存储过程一样,通过 EXECUTE 语句执行。
用户定义函数用CREATE FUNCTION 创建,用 ALTER FUNCTION 修改,用 DROP FUNCTION 除去。
create table test(id int primary key,name char(10))
insert into test values(1,'test1')
insert into test values(2,'test2')
insert into test values(3,'test3')
insert into test values(4,'test4')
1、标量函数
create function return_count()
returns int
as
begin
declare @count int
select @count=count(*) from test
return @count
end
--调用
select dbo.return_count() cont --count为显示的列头
--运行结果
--count
--4

2、内嵌表值函数
create function return_test()
returns table
as
--begin 内联表值函数不能用begin-end
return select name from test
--end
--调用
select * from return_test()
--运行结果
--name
--test1
--test2
--test3
--test4

3、多语句表值函数
create function return_test_multi()
returns @temp table(id int,name char(10))
as
begin
insert into @temp select * from test where id in(1,2)
return --记住,一定不要忘记写return
end
--调用
select * from dbo.return_test_multi()
--运行结果
--id name
--1 test1
--2 test2 
本文介绍了如何在SQL中创建和使用三种类型的用户定义函数:标量函数、内嵌表值函数及多语句表值函数,并提供了具体的创建与调用示例。
1万+

被折叠的 条评论
为什么被折叠?



