创建用户定义函数,它是返回值的已保存的 Transact-SQL 例程。用户定义函数不能用于执行一组修改全局数据库状态的操作。与系统函数一样,用户定义函数可以从查询中唤醒调用。也可以像存储过程一样,通过 EXECUTE 语句执行。 用户定义函数用CREATE FUNCTION 创建,用 ALTERFUNCTION 修改,用 DROPFUNCTION 除去。 createtable test(id intprimarykey,name char(10)) insertinto test values(1,'test1') insertinto test values(2,'test2') insertinto test values(3,'test3') insertinto test values(4,'test4') 1、标量函数 createfunction return_count() returnsint as begin declare@countint select@count=count(*) from test return@count end --调用 select dbo.return_count() cont --count为显示的列头 --运行结果 --count --4 2、内嵌表值函数 createfunction return_test() returnstable as --begin 内联表值函数不能用begin-end returnselect name from test --end --调用 select*from return_test() --运行结果 --name --test1 --test2 --test3 --test4 3、多语句表值函数 createfunction return_test_multi() returns@temptable(id int,name char(10)) as begin insertinto@tempselect*from test where id in(1,2) return--记住,一定不要忘记写return end --调用 select*from dbo.return_test_multi() --运行结果 --id name --1 test1 --2 test2
创建用户定义函数,它是返回值的已保存的 Transact-SQL 例程。用户定义函数不能用于执行一组修改全局数据库状态的操作。与系统函数一样,用户定义函数可以从查询中唤醒调用。也可以像存储过程一样,通过 EXECUTE 语句执行。用户定义函数用CREATE FUNCTION 创建,用 ALTER FUNCTION 修改,用 DROP FUNCTION 除去。create table test(