我有一个proc我需要根据条件执行4个不同的查询,如果第一个查询的结果为0那么它应该执行第二个查询等等 我使用@@ RowCount查找行计数,然后传递值。这是我的代码:
ALTER PROCEDURE FetchingValues @StartLocation Varchar(200),@EndLocation Varchar(200)
AS
DECLARE
@Count NUMERIC
BEGIN
if @@ROWCOUNT=0
BEGIN
select DISTINCT TOP 1 t1.Train_No,Max(t1.Distance) as TotalDistance,0 as Waiting_Time
from Rail t1
where t1.Source_Station_Name Like @StartLocation+'%'
and t1.Destination_Station_Name Like @EndLocation+'%'
GROUP BY t1.Train_No
Order BY TotalDistance ASC
SET @Count= (SELECT @@ROWCOUNT)
SELECT @@ROWCOUNT
END
ELSE if @Count <> 1
BEGIN
EXEC Connection1 @StartLocation,@EndLocation
SET @Count=(SELECT @@ROWCOUNT)
SELECT @@ROWCOUNT
END
ELSE if @Count <> 1
BEGIN
EXEC Connection2 @StartLocation,@EndLocation
SET @Count=(SELECT @@ROWCOUNT)
SELECT @@ROWCOUNT
END
ELSE
BEGIN
select DISTINCT TOP 1 (t1.Train_No+','+ t2.Train_No+','+t3.Train_No+','+t4.Train_No) as TrainSeq,
Max(t1.Distance)+Max(t2.Distance)+Max(t3.Distance)+Max(t4.Distance)as TotalDistance
from Rail t1
join Rail t2 on (t2.Source_Station_Name=t1.Destination_Station_Name)
Join Rail t3 on (t3.Source_Station_Name=t2.Destination_Station_Name)
Join Rail t4 on (t4.Source_Station_Name=t3.Destination_Station_Name)
where t1.Source_Station_Name Like @StartLocation+'%'
and t2.Destination_Station_Name Like @EndLocation+'%'
Group by t1.Train_No,T2.Train_No,t3.Train_No,t4.Train_No
ORDER BY TotalDistance ASC
END
我想通过传递2个值来执行查询,然后我应检查所有查询并获得输出
答案 0 :(得分:0)
如果你需要抑制空结果集,那么只有一种方法 - insert exec
进入临时表并检查是否存在任何结果。如果有记录 - 无需运行下一个查询,只需从#。
BEGIN
select DISTINCT TOP 1 t1.Train_No,Max(t1.Distance) as TotalDistance,0 as Waiting_Time
into #t -- <<<<<<
from Rail t1
where t1.Source_Station_Name Like @StartLocation+'%'
and t1.Destination_Station_Name Like @EndLocation+'%'
GROUP BY t1.Train_No
if not exists(select 1 from #t)
BEGIN
insert #t
EXEC Connection1 @StartLocation,@EndLocation
END
if not exists(select 1 from #t)
BEGIN
insert #t
EXEC Connection2 @StartLocation,@EndLocation
END
if not exists(select 1 from #t)
...
/* finally */
select * from #t
Order BY TotalDistance ASC
END