SQL Server函数——表值函数和标量函数

create table student
(
 sid int identity primary key,
 sname varchar(20),
 gender tinyint,
 age int
)
go
insert into student values('赵四',0,22)
insert into student values('钱五',0,33)
insert into student values('孙六',0,44)
go
---表值函数主要用于数据计算出来返回结果集,可以带参数(这是和视图的一个大的区别)
----表值函数返回结果集:函数中没有过多的逻辑处理,如变量的定义、判断等
create function Fun_studentInsert(@sid int)
returns table
as
return
(
 select * from student where sid=@sid
)
go
---调用
select * from dbo.fun_studentInsert(1)
go
----如果函数中定义变量,进行判断计算处理,写法就不一样了。要定义表变量才行,表值函数里是不允许创建临时表的,只能是表变量
create function fun_studentselect(@sid int)
returns @Table table(sname varchar(20),gender tinyint,age int)
as
  begin
    declare @a tinyint
    select @a=gender from student where sid=@sid
    insert @Table values('李七',@a,14)--表变量里定义的猎术和取值列数要一致
    return
  end
go
----调用
insert into student select * from dbo.fun_studentselect(2)

select * from student
go

----如果进行多表操作,可以在函数体内定义表变量来存放结果集再进行关联查询
----标量函数
create function fun_age(@Time datetime)
returns int
as
  begin
    declare @age int
    set @age=year(getdate())-year(@Time)
    return @age
  end
go
--访问标量函数一般在函数名前加dbo,不然会被认为是系统内置函数,却因又不是系统内置函数而报错。
select dbo.fun_age('1990-05-25')


--表变量和临时表的区别及函数和存储过程的区别,大伙可以在博客园上博一把,有很多说明文章比较详细的了。
 

猜你喜欢

转载自blog.csdn.net/ljxqsqmoliwei/article/details/46356999