:) 下面是邹建老大写的,从 WHILE @@ROWCOUNT>0 开始,注解一下这样定的原理与及一些语法上的应用。 --测试数据 CREATE TABLE table_Bus( BusID nvarchar(10), BusStation nvarchar(10), BusStationIndex int) INSERT table_Bus SELECT N'8路' ,N'站A',1 UNION ALL SELECT N'8路' ,N'站B',2 UNION ALL SELECT N'8路' ,N'站C',3 UNION ALL SELECT N'8路' ,N'站D',4 UNION ALL SELECT N'8路' ,N'站J',5 UNION ALL SELECT N'8路' ,N'站L',6 UNION ALL SELECT N'8路' ,N'站M',7 UNION ALL SELECT N'20路' ,N'站G',1 UNION ALL SELECT N'20路' ,N'站H',2 UNION ALL SELECT N'20路' ,N'站I',3 UNION ALL SELECT N'20路' ,N'站J',4 UNION ALL SELECT N'20路' ,N'站L',5 UNION ALL SELECT N'20路' ,N'站M',6 UNION ALL SELECT N'255路',N'站N',1 UNION ALL SELECT N'255路',N'站O',2 UNION ALL SELECT N'255路',N'站P',3 UNION ALL SELECT N'255路',N'站Q',4 UNION ALL SELECT N'255路',N'站J',5 UNION ALL SELECT N'255路',N'站D',6 UNION ALL SELECT N'255路',N'站E',7 UNION ALL SELECT N'255路',N'站F',8 GO
SQL code
--线路查询存储过程 CREATEPROC p_qry
@Station_Startnvarchar(10),
@Station_Stopnvarchar(10)
ASSET NOCOUNT ONDECLARE@lintSET@l=0SELECT BusID,BusStation,
Line=CAST('('+RTRIM(BusID)+': '+RTRIM(BusStation) asnvarchar(4000)),
BusStationIndex=BusStationIndex,
Level=@l,
gid=1INTO # FROM table_Bus
WHERE BusStation=@Station_StartWHILE@@ROWCOUNT>0ANDNOTEXISTS(SELECT*FROM # WHERE BusStation=@Station_StopORLEN(Line)=4000)
BEGINSET@l=@l+1INSERT #(Line,BusID,BusStation,BusStationIndex,Level,gid)
SELECT
Line=a.Line+CASEWHEN a.BusID=b.BusID THEN N'->'+RTRIM(b.BusStation)
ELSE N') => ('+RTRIM(b.BusID)
+N': '+RTRIM(b.BusStation) END,
b.BusID,b.BusStation,b.BusStationIndex,@l,
CASEWHEN a.BusID=b.BusID THEN a.gid ---?when是什么语法哦帮助也没找到ELSE a.gid+1ENDFROM # a,table_Bus b
WHERE a.Level=@l-1AND(
a.BusID=b.BusID AND(
a.BusStationIndex=b.BusStationIndex+1OR
a.BusStationIndex=b.BusStationIndex-1)
OR
a.BusStation=b.BusStation AND a.BusID<>b.BusID)
ENDSELECT N'起点站'=@Station_Start
,N'终点站'=@Station_Stop
,N'转车次数'=gid-1
,N'经过站数'=CASEWHEN gid<3THEN@lELSE@l-gid+2END
,N'乘车线路'=Line+N')'FROM #
WHERELevel=@lAND BusStation=@Station_StopIF@@ROWCOUNT=0SELECT*FROM #
GO