存储过程实现返回一个表格,
简单来说就是根据一个表的 某几列,运算出其他信息,然后整合后,返回表。
目前的存储过程如下: resultTable表检索出1000条数据,整个存储过程用了5分钟,不是一般的慢啊!!!
ALTER proc [dbo].[P_GetCntInRussiaNotReturn] as
DECLARE @tmp TABLE (
cnt_no nvarchar(50),
cnt_size nvarchar(50),
cnt_type nvarchar(50),
cnt_category nvarchar(50),
nowDate datetime,
firstInDate datetime,
firstInCity nvarchar(50),
endDate datetime,
inDays decimal
);
with resultTable as(
select cnt_no,cnt_size,cnt_type,cnt_category,in_yard_time from dbo.v_cnt_ie_state
where cnt_category='STC' and
at_country='俄罗斯' and cnt_work_state='在场'
union all
select cnt_no,cnt_size,cnt_type,cnt_category,out_yard_time_last from dbo.v_cnt_ie_state
where cnt_category='STC' and country_name='俄罗斯' and cnt_work_state='在途'
)
insert into @tmp (cnt_no,cnt_size,cnt_type,cnt_category,nowDate,firstInDate,firstInCity,endDate,inDays)
select cnt_no,cnt_size,cnt_type,cnt_category,in_yard_time,null,'',getdate(),null from resultTable
declare c_find cursor for select cnt_no,nowDate from @tmp
open c_find
declare @strCntno varchar(50)
declare @inYardTime datetime
declare @firstInTime datetime
declare @firstInCity varchar(500)
fetch next from c_find into @strCntno,@inYardTime
while @@fetch_status = 0
begin
select top 1 @firstInTime=in_yard_time,@firstInCity=city_name
from v_cnt_ie_state where in_yard_time<= @inYardTime
and cnt_no=@strCntno
and at_country='俄罗斯'and country_name='中国'
order by create_time desc
update @tmp set firstInDate=@firstInTime,firstInCity=@firstInCity,
inDays=datediff(day,@firstInTime,getdate())+1
where cnt_no=@strCntno
fetch next from c_find into @strCntno,@inYardTime
end
CLOSE c_find
DEALLOCATE c_find
select cnt_no,cnt_size,cnt_type,cnt_category,convert(varchar(10),firstInDate,120) firstInDate
,firstInCity,convert(varchar(10),endDate,120) endDate,inDays
from @tmp order by firstInDate
GO
------解决思路----------------------
一句搞定,自己把视图替换掉
WITH resulttable AS (
SELECT cnt_no,
cnt_size,
cnt_type,
cnt_category,
in_yard_time
FROM dbo.v_cnt_ie_state
WHERE cnt_category = 'STC'
AND at_country = '俄罗斯'
AND cnt_work_state = '在场'
UNION ALL
SELECT cnt_no,
cnt_size,
cnt_type,
cnt_category,
out_yard_time_last
FROM dbo.v_cnt_ie_state
WHERE cnt_category = 'STC'
AND country_name = '俄罗斯'
AND cnt_work_state = '在途'
)
SELECT r.cnt_no,
r.cnt_size,
r.cnt_type,
r.cnt_category,
CONVERT(VARCHAR(10),v.firstindate,120) firstindate,
v.firstincity,
CONVERT(VARCHAR(10),Getdate(),120) enddate,
Datediff(DAY,v.firstindate,Getdate())+ 1 indays
FROM result r
CROSS APPLY (
SELECT TOP 1 in_yard_time firstindate,
city_name firstincity
FROM v_cnt_ie_state
WHERE in_yard_time <= r.nowdate
AND cnt_no = r.cnt_no
AND at_country = '俄罗斯'
AND country_name = '中国'
ORDER BY create_time DESC
) v
ORDER BY firstindate