摘要:在SqlServer中用自定义函数返回动态表内容
说明:在SupplyPlan表中,存储着每一个RequestQty及其对应的开始终止日期段;因为我在以后处理中要判断当前天属于哪一条RequestQty的日期区间并进行处理,所以后台数据库只能设计成这种存储形式;但是在页面的显示时候,需要动态的根据每一个SupplyPlanNo生成对应的多条日期区段及其数量显示,所以采用自定义函数形式返回处理以后的动态记录集!返回的字段@AllRequestQty为"1|13|5|8"形式,在asp中就可以采用split函数分组从而动态显示字段。
/*
** add by wls For: convert many lines of SP datas to one char group by vehicle,part
*/
CREATE FUNCTION xzc.fn_getContent_SupplyPlan
(@s_p_no int = NULL,
@viewFlag varchar(1) =
)
RETURNS @fn_getContent_SupplyPlan TABLE
(
ID varchar(8000),
SupplyPlanNo int,
Vehicle varchar(25),
Sort varchar(20),
Part varchar(25),
RequestQty varchar(8000),
Remark varchar(255)
)
AS
BEGIN
DECLARE @sVehicle varchar(25), @sSort varchar(20)
DECLARE @sPart varchar(25), @iVehicle varchar(25)
DECLARE @iPart varchar(25), @sRemark varchar(255)
DECLARE @RequestQty int , @theID int
DECLARE @AllRequestQty varchar(8000), @allID varchar(8000)
select @AllRequestQty =
select @allID =
/*Outer CURSOR*/
DECLARE getVehiclePartSP CURSOR SCROLL FOR
select distinct Vehicle, Sort, Part from SupplyPlan
where SupplyPlanNo = @s_p_no and ViewFlag = @viewFlag
/* --Order by ID desc
select Vehicle, Sort, Part from (select min(ID) as ID, Vehicle, Sort, Part from SupplyPlan
where SupplyPlanNo = @s_p_no group by Vehicle, Sort, Part) a order by a.ID desc
*/
/*Inner CURSOR*/
DECLARE getContentSP CURSOR SCROLL FOR
select ID, Vehicle, Part, RequestQty
from SupplyPlan where SupplyPlanNo = @s_p_no and ViewFlag = @viewFlag order by ID
if @s_p_no IS NULL or @s_p_no =
begin
RETURN
end
OPEN getVehiclePartSP
FETCH first from getVehiclePartSP into @sVehicle,@sSort,@sPart
while(@@fetch_status = 0)
BEGIN
OPEN getContentSP
FETCH first from getContentSP into @theID, @iVehicle, @iPart, @RequestQty
while(@@fetch_status = 0)
BEGIN
if @iVehicle = @sVehicle and @iPart = @sPart
begin
select @allID = @allID + | + convert(varchar(15), @theID)
select @AllRequestQty = @AllRequestQty + | + convert(varchar(25), @RequestQty)
end
FETCH next from getContentSP into @theID, @iVehicle, @iPart, @RequestQty
END
CLOSE getContentSP
select @allID = xzc.trim_char(@allID, |)
select @AllRequestQty = xzc.trim_char(@AllRequestQty, |)
select @sRemark = (select top 1 Remark from SupplyPlan where SupplyPlanNo = @s_p_no
and Vehicle = @sVehicle and Part = @sPart)
INSERT INTO @fn_getContent_SupplyPlan VALUES(@allID, @s_p_no, @sVehicle, @sSort, @sPart, @AllRequestQty, @sRemark)
select @AllRequestQty =
select @allID =
select @sRemark =
FETCH next from getVehiclePartSP into @sVehicle,@sSort,@sPart
END
DEALLOCATE getContentSP
CLOSE getVehiclePartSP
DEALLOCATE getVehiclePartSP
RETURN
END