--建立测试环境
Create Table 表(no integer,val integer)
--插入数据
insert into 表
select '1','19' union
select '2','37' union
select '3','43' union
select '4','98'
select * from 表
--测试语句
select top 1 no,0 from 表
union
select b.no,b.val-a.val from 表 a,表 b
where a.no=b.no-1
--创建函数得到val2
CREATE FUNCTION [dbo].[Fun_Test]
(
@intNo INT
)RETURNS INT
AS
BEGIN
declare @rtValue INT
select @rtValue = +(max(val)-min(val)) from (
Select top 2 val From table1 Where no1<=@intNo
order by no1 desc) a
Return (ISNULL(@rtValue,0))
END
go
--建测试表
Create Table table1(no1 int,val int)
go
--插入测试记录
Insert into table1 values (1,19)
Insert into table1 values (2,37)
Insert into table1 values (3,43)
Insert into table1 values (4,98)
go
--查询
select no1,val,dbo.Fun_Test(no1) from table1
go
--删除函数和测试表
Drop FUNCTION [dbo].[Fun_Test]
Drop Table table1