SQL中Table型数据与用户自定义函数(downmoon)
SQL Server 2000 新增了Table型数据:Table型数据不能用来定义列的类型,只能用作T-SQL变量或者作为自定义函数的返回值,下例是一个简单的table 型数据的例子:
Declare
@TableVar
Table
(Cola int Primary Key ,Colb char ( 3 ))
Insert Into @TableVar Values ( 1 , ' abc ' )
Insert Into @TableVar Values ( 2 , ' def ' )
Select * From @TableVar
(Cola int Primary Key ,Colb char ( 3 ))
Insert Into @TableVar Values ( 1 , ' abc ' )
Insert Into @TableVar Values ( 2 , ' def ' )
Select * From @TableVar
以上语句定义了一个名为TableVar,有两列的table 型变量像通常的表一样table 型数据也有insert select 等操作。在SQL Server 2000 中table 型数据与用户自定义函数是密不可分的,SQL Server 2000支持两种类型的函数:内置函数和用户定义函数。内置函数只允许T-SQL 语句调用而不能更改使用。用户定义函数可以根据需要定义自己所需的函数。用户定义函数可以带参数,也可以不带参数,但只能返回单值。正是由于这个原因SQL Server 2000 增加了table 型数据 ,其值可以是整型字符型或数值型。下例是一个简单的用户定义函数说明了用户定义函数的基本结构:
Create
Function
CubicVolume
( @CubeLength decimal ( 4 , 1 ), @CubeWidth decimal ( 4 , 1 ), @CubeHeight decimal ( 4 , 1 ) )
Returns decimal ( 12 , 3 )
As
Begin
Return ( @CubeLength * @CubeWidth * @CubeHeight )
End
-- SELECT AppDta.dbo.CubicVolume (10,8,6)
( @CubeLength decimal ( 4 , 1 ), @CubeWidth decimal ( 4 , 1 ), @CubeHeight decimal ( 4 , 1 ) )
Returns decimal ( 12 , 3 )
As
Begin
Return ( @CubeLength * @CubeWidth * @CubeHeight )
End
-- SELECT AppDta.dbo.CubicVolume (10,8,6)
在上例中用CREATE FUNCTION 创建了一个函数CubicVolume 来计算立方体的体积,变量CubeLength CubeWidth CubeHeight 为输入参数,返回值为数值型。BEGIN 表明函数体的开始,END 表明函数体的结束。通过下例 我们就会清楚用户定义函数与table 型数据是如何有机结合的:
Use
pubs
Create Function SalesByStore( @storeid varchar ( 30 ))
Returns Table
As
Return ( Select title, qty From sales s, titles t
Where s.stor_id = @storeid and t.title_id = s.title_id)
-- select * from sales
SELECT Pubs.dbo.SalesByStore( 7131 )
Create Function SalesByStore( @storeid varchar ( 30 ))
Returns Table
As
Return ( Select title, qty From sales s, titles t
Where s.stor_id = @storeid and t.title_id = s.title_id)
-- select * from sales
SELECT Pubs.dbo.SalesByStore( 7131 )
邀月注:本文版权由邀月 和CSDN共同所有,转载请注明出处。
助人等于自助! 3w@live.cn